Python+Selenium學習--下載文件


場景

webdriver 允許我們設置默認的文件下載路徑。也就是說文件會自動下載並且存在設置的那個目錄中,下面以firefox及chrome為例

代碼

Firefox下載

為了讓Firefox瀏覽器能實現文件下載,需要通過FirefoxProfile()對其做一些設置。

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

browser.download.manager.showWhenStarting  :是否顯示開始:True為顯示開始,Flase為不顯示開始。

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

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

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

#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: firefox下載文件.py
@time: 2018-09-26 16:07
@desc:
'''
from selenium import webdriver
import os,time

fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",0)
fp.set_preference("browser.download.manager.showhenStarting",True)
fp.set_preference("browser.download.dir",os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","binary/octet-stream")#下載文件類型

driver = webdriver.Firefox(firefox_profile = fp)
driver.get("http://pypi.Python.org/pypi/selenium")
driver.find_element_by_xpath("//a[@id='files-tab']").click()
time.sleep(5)

#選擇下載文件
driver.find_element_by_xpath("//a[contains(@href,'.tar.gz')]").click()
time.sleep(30)

driver.quit()

  

Chrome下載

download.default_directory:設置下載路徑

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

#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: chrome下載.py
@time: 2018-09-26 16:32
@desc:
'''
from selenium import webdriver
import time

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='F:\chromedriver\chromedriver.exe', chrome_options=options)
driver.get("http://pypi.Python.org/pypi/selenium")
driver.find_element_by_xpath("//a[@id='files-tab']").click()
time.sleep(5)

#選擇下載文件
driver.find_element_by_xpath("//a[contains(@href,'.tar.gz')]").click()
time.sleep(30)
driver.quit()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM