如何扩展我的代码以包含多年?[关闭]

How do I extend my code to include multiple years? [closed]

提问人:the_special_none 提问时间:11/17/2023 更新时间:11/17/2023 访问量:35

问:


编辑问题以包括所需的行为、特定问题或错误以及重现问题所需的最短代码。这将帮助其他人回答这个问题。

2天前关闭。

我正在尝试从官方网站收集戴维斯杯比赛的数据。我能够使用 Python 的 Selenium 为 2018 年世界组的所有比赛和球员退役,并且我正在尝试为前几个赛季创建代码。但是,我无法打开下拉菜单并选择不同的年份或更改当前选择的年份(2018 年)。关于如何在此aspx网页上迭代不同年份的任何想法?

我试图抓取戴维斯杯不同年份的数据。我能够收集一年的数据,但我无法进一步开发我的代码并包括多年。

python selenium-webdriver web-scraping 下 拉菜单

评论

0赞 Shawn 11/17/2023
展示您的代码试用版并分享您遇到的错误。

答:

0赞 Shawn 11/17/2023 #1

我不知道您面临的实际问题,因为您没有共享代码或错误堆栈跟踪。我只是为您提供了单击不同下拉项的代码。

请参阅以下代码并附有内联说明:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.daviscup.com/en/draws-results/historic-format/world-group.aspx")
driver.maximize_window()
wait = WebDriverWait(driver, 15)

# Click on Accept All Cookies button
acceptCookie_Btn = wait.until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler")))
driver.execute_script("arguments[0].click();", acceptCookie_Btn)

# Click on the dropdown arrow
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='selected']//div[@class='arrow']"))).click()
# Click on dropdown item 2016, if you want to click some other year, just change the year in the below XPath expression
wait.until(EC.element_to_be_clickable((By.XPATH, "//a[text()='2016']"))).click()

结果:

enter image description here