简体   繁体   English

Selenium 花费太多时间来下载文件

[英]Selenium taking too much time to download files

I am using this part of my code to download a some files which I download from clicking a link with a partial text specified, but even with my driver.implicitly_wait(5) , the driver is taking more then 2 minutes to check and download available files.我正在使用这部分代码来下载一些文件,我通过单击指定部分文本的链接下载这些文件,但即使使用我的driver.implicitly_wait(5) ,驱动程序也需要超过 2 分钟来检查和下载可用文件。

What's the best pythonic way to do the same as code below?与下面的代码相同的最佳pythonic方法是什么?

IMPORTANT, sometimes only one or two of the 4 files are available to download.重要提示,有时 4 个文件中只有一两个可供下载。

driver.find_element_by_xpath('//*[@id="menu"]/li[2]/a').click()
driver.find_element_by_xpath('//*[@id="linkbtconsultar"]/a[1]/span').click()

try:
    driver.find_element_by_partial_link_text('ASD!').click()
except NoSuchElementException:
    return
try:
     driver.find_element_by_partial_link_text('QWE#').click()
except NoSuchElementException:
     return
try:
    driver.find_element_by_partial_link_text('RTY%').click()
except NoSuchElementException:
    return
try:
    driver.find_element_by_partial_link_text('ASD%').click()
except NoSuchElementException:
    return

I would combine the 4 locators into one, return a collection of elements, and then loop through the collection clicking on each one.我会将 4 个定位器合二为一,返回一组元素,然后在每个元素上单击循环遍历该集合。

Something like this:像这样的东西:

driver.find_element_by_xpath('//*[@id="menu"]/li[2]/a').click()
driver.find_element_by_xpath('//*[@id="linkbtconsultar"]/a[1]/span').click()
docs = driver.find_elements_by_xpath('//a[contains(.,'ASD!')] | //a[contains(.,'QWE#')] | //a[contains(.,'RTY%')] | //a[contains(.,'ASD%')]')
for doc in docs:
    doc.click()
    # you probably will need a brief wait here to give the browser time to process each click

This code will try to get all the desired docs and only return ones that exist... but it should be immediate.此代码将尝试获取所有所需的文档,并且只返回存在的文档……但它应该是即时的。

You might also consider not using Selenium to download the files and importing the requests module to do so.您也可以考虑不使用 Selenium 下载文件并导入 requests 模块来执行此操作。 You could then use something like map to download all files at once.然后,您可以使用类似map 的东西一次下载所有文件。

try:
    files = driver.find_elements_by_partial_link_text('file or extension')[:4]
except NoSuchElementException:
    return
for file in files:
    file.click()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM