Selenium 文件上传下载

文件上传

对于input上传,直接send_keys即可

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('http://sahitest.com/demo/php/fileUpload.htm')
#上传文件
upload = driver.find_elements_by_id('file')[0]
upload.send_keys("D:\\test.txt")
driver.find_elements_by_name('submit')[0].click()
time.sleep(2)

driver.quit()

文件下载

#Chrome下载

from selenium import webdriver
from time import sleep

options = webdriver.ChromeOptions()
prefs = {
    'profile.default_content_settings.popups': 0, #设置为 0 禁止弹出窗口
    'download.default_directory': 'd:\\' #设置下载路径
    }
options.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome(chrome_options=options)
driver.get('http://sahitest.com/demo/saveAs.htm')
driver.find_element_by_xpath('//a[text()="testsaveas.zip"]').click()
sleep(3)
driver.quit()
#Firefox下载

from selenium import webdriver
from time import sleep

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.dir', 'd:\\')  #指定下载保存路径
profile.set_preference('browser.download.folderList', 2) #设置浏览器下载路径,0表示默认,2表示指定路径
profile.set_preference('browser.download.manager.showWhenStarting', False) #是否显示开始
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip') #设置默认免提示文件类型

driver = webdriver.Firefox(firefox_profile=profile)

driver.get('http://sahitest.com/demo/saveAs.htm')
driver.find_element_by_xpath('//a[text()="testsaveas.zip"]').click()
sleep(3)
driver.quit()

 

posted @ 2020-10-24 23:26  Water_you  阅读(170)  评论(0编辑  收藏  举报