selenium学习——文件上传/下载

1、上传

学习链接:

https://www.cnblogs.com/yoyoketang/p/6445270.html

input标签可以借助send_keys()操作来实现文件上传

<<input type="file" name="file" style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;">>

参考代码如下:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time


option = webdriver.ChromeOptions()
option.add_argument(r'--user-data-dir=C:\Users\yl8\AppData\Local\Google\Chrome\User Data1')
driver = webdriver.Chrome(options=option)
# driver.get("http://www.cnblogs.com/")
blogurl = "http://www.cnblogs.com/"
myblog = blogurl + "my"
driver.get(myblog)
driver.refresh()
driver.find_element_by_id("blog_nav_newpost").send_keys(Keys.ENTER)
time.sleep(10)
driver.find_element_by_xpath('//*[@id="post-title"]').send_keys(edit_title)# 点开编辑器图片
driver.find_element_by_css_selector("img.mceIcon").click()
time.sleep(3)
# 定位所有iframe,取第二个
iframe = driver.find_elements_by_tag_name("iframe")[1]
# 切换到iframe上
driver.switch_to.frame(iframe)
# 文件路径
driver.find_element_by_name("file").send_keys(r"xxx\图片.jpg")

 2、文件下载

参考代码:

import os
from selenium import webdriver


options = webdriver.ChromeOptions()
# 设置为0,表示禁止弹出下载窗口,os.getcwd()获取当前脚本的目录作为下载文件的保存位置
prefs = {'profile.default_content_settings.popups':0,
         'download.default_directory':os.getcwd()}
options.add_experimental_option('prefs',prefs)
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://pypi.org/project/selenium/#files")
driver.find_element_by_partial_link_text("selenium-3.141.0.tar.gz").click()

 

posted @ 2020-05-07 16:50  Penny悦  阅读(194)  评论(0编辑  收藏  举报