【问题标题】:Use Selenium to download file by clicking "javascript:__doPostBack('LeaderBoard1$cmdCSV','')"通过单击“javascript:__doPostBack('LeaderBoard1$cmdCSV','')”使用 Selenium 下载文件
【发布时间】:2020-09-12 20:46:12
【问题描述】:

我想通过自动化下载一堆棒球统计数据的 CSV 文件,可以在以下位置找到:https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age=0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31。将表格下载为 CSV 的按钮标记为“导出数据”。

HTML:

<div class="br_dby">
    <span style="float: left">
        <a href="javascript:ShowHide();">Show Filters</a>  
            |  
        <a href="#custom">Custom Reports</a>
    </span>
    <a href="javascript:__doPostBack('LeaderBoard1$cmdCSV','')" id="LeaderBoard1_cmdCSV">Export Data</a>
</div>

如您所知,该按钮不是指向下载页面的重定向(在这种情况下,requests 可用于下载文件),而是一个过程。

代码:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
binary = r'C:\Program Files\Mozilla Firefox\firefox.exe'
options = Options()
options.headless = True
options.binary = binary
options.set_preference("browser.download.folderList",2)
options.set_preference("browser.download.manager.showWhenStarting", True)
options.set_preference("browser.download.dir", r"C:\Users\jlpyt\Downloads")
driver = webdriver.Firefox(options=options, executable_path=r"C:\Users\jlpyt\geckodriver-v0.27.0-win32\geckodriver.exe")
driver.get('https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type=0&season=2020&month=0&season1=2020&ind=0&team=0&rost=0&age=0&filter=&players=0&startdate=2020-01-01&enddate=2020-12-31')
elem = driver.find_element_by_id('LeaderBoard1_cmdCSV')
elem.click()

使用此代码,Selenium 能够单击按钮,但不会启动下载。有什么方法可以让我使用 Selenium 点击按钮并下载文件?或者,有没有我没有想到的替代方法?

【问题讨论】:

    标签: python selenium selenium-webdriver webdriverwait dopostback


    【解决方案1】:

    该元素为__doPostBack启用元素,所以点击该元素需要诱导WebDriverWaitelement_to_be_clickable(),可以使用以下Locator Strategies之一:

    • 使用ID

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "LeaderBoard1_cmdCSV"))).click()
      
    • 使用LINK_TEXT

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Export Data"))).click()
      
    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#LeaderBoard1_cmdCSV"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='LeaderBoard1_cmdCSV']"))).click()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      
    • 浏览器快照:


    参考

    您可以在以下位置找到一些相关讨论:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2020-02-10
      • 2018-09-08
      相关资源
      最近更新 更多