python+selenium下载和上传文件

操作浏览器上传文件,先看代码

 1 """
 2 * send_keys() 指定文件上传路径。
 3 """
 4 from selenium import webdriver
 5 import os
 6 
 7 file_path = os.path.abspath('./files/')
 8 
 9 driver = webdriver.Chrome()
10 upload_page = 'file:///' + file_path + 'upfile.html'
11 driver.get(upload_page)
12 
13 # 定位上传按钮,添加本地文件
14 driver.find_element_by_id("file").send_keys(file_path + 'test.txt')
15 # ……

下载文件(火狐和谷歌有区别,所有分开写)

 1 """
 2 chrome浏览器实现下载
 3 """
 4 import os
 5 from selenium import webdriver
 6 
 7 options = webdriver.ChromeOptions() 
 8 prefs = {'profile.default_content_settings.popups': 0,  #下载不弹窗
 9          'download.default_directory': os.getcwd()}     #下载路径
10 options.add_experimental_option('prefs', prefs) 
11 
12 driver = webdriver.Chrome(chrome_options=options) 
13 driver.get("https://pypi.org/project/selenium/#files")
14 driver.find_element_by_partial_link_text("selenium-3.141.0.tar.gz").click()

 
1
""" 2 firefox浏览器实现下载 3 """ 4 import os 5 from selenium import webdriver 6 7 fp = webdriver.FirefoxProfile() 8 9 fp.set_preference("browser.download.folderList", 2) 10 fp.set_preference("browser.download.dir", os.getcwd()) 11 fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "binary/octet-stream") 12 13 driver = webdriver.Firefox(firefox_profile=fp) 14 driver.get("https://pypi.org/project/selenium/#files") 15 driver.find_element_by_partial_link_text("selenium-3.141.0.tar.gz").click()
posted @ 2019-12-29 20:12  Harry_666  阅读(589)  评论(0编辑  收藏  举报