Python+selenium之下載文件

1、Firefox文件下載

Web允許咱們設置默認的文件下載路勁,文件會自動下載而且存放在指定的目錄下。html

 1 from selenium import webdriver
 2 import os
 3 fp = webdriver.FirefoxProfile()
 4 fp.set_preference("browser.download.folderList",0)
 5 fp.set_preference("browser.download.manager.showhenStarting",True)
 6 fp.set_preference("browser.download.dir",os.getcwd())
 7 fp.set_preference("browser.helperApps.neverAsk.saveToDisk","applaction/octet-stream")#下載文件類型
 8 
 9 driver = webdriver.Firefox(firefox_profile = fp)
10 driver.get("http://pypi.Python.org/pypi/selenium")
11 driver.find_element_by_xpath("//*[@id='download-button']/a").click()
12 
13 driver.find_element_by_xpath("//*[@id='content']/div[3]/table/tbody/tr[3]/td[1]/span/a[1]").click()

爲了讓Firefox瀏覽器能實現文件下載,須要經過FirefoxProfile()對其作一些設置。web

browser.download.foladerList :設置成0表明下載到瀏覽器默認下載路徑,設置成2則能夠保存到指定的目錄。chrome

browser.download.manager.showWhenStarting  :是否顯示開始:True爲顯示開始,Flase爲不顯示開始。瀏覽器

browser.download.dir :用於指定所下載文件的目錄。app

os.getcwd()函數不須要傳遞參數。用於返回當前的目錄。函數

browser.helperApps.neverAsk.saveToDisk  :對所給文件類型再也不彈出框進行詢問。ui

 

 1 from selenium import webdriver
 2 from time import sleep
 3 
 4 profile = webdriver.FirefoxProfile()
 5 profile.set_preference('browser.download.dir', 'd:\\')  #如今文件存放的目錄
 6 profile.set_preference('browser.download.folderList', 2)
 7 profile.set_preference('browser.download.manager.showWhenStarting', False)
 8 profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/zip')
 9 
10 driver = webdriver.Firefox(firefox_profile=profile)
11 
12 driver.get('http://sahitest.com/demo/saveAs.htm')
13 #driver.find_element_by_xpath('//a[text()="testsaveas.zip"]').click()
14 driver.find_element_by_xpath('/html/body/a[1]').click()
15 sleep(20)
16 driver.quit()

 

 

 

2、Chrome文件下載
spa

download.default_directory:設置下載路徑firefox

profile.default_content_settings.popups:設置爲0禁止彈出窗口code

from selenium import webdriver 

from time import sleep
options = webdriver.ChromeOptions()
prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': 'd:\\'}
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(executable_path='D:\\chromedriver.exe', 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()
相關文章
相關標籤/搜索