场景
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 :对所给文件类型不再弹出框进行询问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#!/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禁止弹出窗口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/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()
|
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。