如何使用Selenium在点击事件中下载文件? [英] How can I download a file on a click event using selenium?

查看:992
本文介绍了如何使用Selenium在点击事件中下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究python和selenium.我想使用硒从单击事件中下载文件.我写了下面的代码.

I am working on python and selenium. I want to download file from clicking event using selenium. I wrote following code.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")

browser.close()

我想从给定的URL中从名称为"Export Data"的链接下载两个文件.我该如何实现它,因为它仅适用于click事件?

I want to download both files from links with name "Export Data" from given url. How can I achieve it as it works with click event only?

推荐答案

使用find_element(s)_by_*查找链接,然后调用click方法.

Find the link using find_element(s)_by_*, then call click method.

from selenium import webdriver

# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

browser = webdriver.Firefox(profile)
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")

browser.find_element_by_id('exportpt').click()
browser.find_element_by_id('exporthlgt').click()

添加了配置文件操作代码以防止出现下载对话框.

Added profile manipulation code to prevent download dialog.

这篇关于如何使用Selenium在点击事件中下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆