我想通过自动化下载一堆棒球统计数据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单击按钮并下载文件?或者,有没有我没有想到的替代方法?
元素是__doPostBack
enabled元素,因此要单击,就需要为引入WebDriverWait,element_to_be_clickable()
并且可以使用以下两种定位策略之一:
使用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
浏览器快照:
您可以在以下位置找到一些相关的讨论:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句