python - 使用 Selenium 从分类为列表框的按钮中选择值

标签 python selenium

我想从这个网站抓取数据:

https://www.sofascore.com/tournament/football/england/premier-league/17

我想获取几个季节的数据,因此我需要使用此按钮进行更改。

link

问题是这个列表实际上被指定为按钮:

<button type="button" id="downshift-2-toggle-button" aria-haspopup="listbox" aria-expanded="false" aria-labelledby="downshift-2-label downshift-2-toggle-button" class="sc-fEXmlR bwfzPL"><div display="flex" class="sc-hLBbgP sc-eDvSVe gjJmZQ fRddxb"><span color="onSurface.nLv1" class="sc-bqWxrE ieHJKE">22/23</span><svg width="24" height="24" viewBox="0 0 24 24" fill="#222226" class="sc-jSUZER btAxHh" style=""><path fill="#222226" d="M7 10L12 15 17 10z"></path></svg></div></button>

我尝试这样做:

dropdown = driver.find_element_by_xpath("//li//button[@id='downshift-2-toggle-button']")
sel = Select(dropdown)
sel.select_by_visible_text("21/22")

但是它不起作用。

最佳答案

这不是“Select”类型的下拉列表,而是“li”类型的下拉列表,因此您不能使用“Select”,而是尝试以下代码:

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options = options)
driver.implicitly_wait(15)
driver.maximize_window()
driver.get("https://www.sofascore.com/tournament/football/england/premier-league/17")

driver.find_element(By.CSS_SELECTOR, ".sc-fnGiBr.kdHYZX #downshift-2-toggle-button").click()
time.sleep(1)
list_of_options = driver.find_elements(By.XPATH, ".//div/ul[@id='downshift-2-menu']/li")

option_to_select = "93/94"

for i in range(len(list_of_options)):
    option = driver.find_element(By.XPATH, ".//div/ul[@id='downshift-2-menu']/li[" + str(i + 1) + "]").text
    time.sleep(0.2)
    driver.find_element(By.XPATH, ".//div/ul[@id='downshift-2-menu']/li[" + str(i + 1) + "]").location_once_scrolled_into_view
    if option_to_select == option:
        driver.find_element(By.XPATH, ".//div/ul[@id='downshift-2-menu']/li[" + str(i + 1) + "]").click()
        break

关于python - 使用 Selenium 从分类为列表框的按钮中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75112059/

相关文章:

python - 如何使用 matplotlib 更新图形

python - 如果按下某个键,我怎样才能暂时真正休息? [Python]

python - 高效的 numpy.cumsum 和 numpy.digitize

python - 在Python中使用正则表达式解析LaTeX代码

python - Selenium 错误加载页面

python - 如何关闭Selenium中的弹出窗口

python - Python 中的网页抓取

java - 无法@Autowire配置

java - 如何计算 HTML 结构中的列表数量 (Selenium)

python - selenium 和 python3 : selecting search box on www. rottentomatoes.com