我正在使用 python 测试 selenium,我需要从下拉列表中选择一个选项。
在这种情况下,我正在使用网站进行测试https://www.motogp.com/es/gp-results/2024/qat/motogp/rac/classification,我需要将 rac 选项更改为任何其他 spr例如,因为直接在网络上更改它会重定向到 rac。
我已经尝试过:
select_element = driver.find_element(By.CLASS_NAME, "primary-filter__filter-select--cat")
select = Select(select_element)
但是,我无法选择该选项。我想正确获取网址。
问题在此代码中:
By.CLASS_NAME, "primary-filter__filter-select--cat"
解决方案:使用如下XPath定位器策略
By.XPATH, "(//select[@class='primary-filter__filter-select primary-filter__filter-select--cat'])[2]"
XPath表达式解释:
(//select[@class='primary-filter__filter-select primary-filter__filter-select--cat'])[2]
-- 在 HTML 文档中定位具有指定类属性值 <select>
的第二个下拉列表元素 (primary-filter__filter-select primary-filter__filter-select--cat
) 这是完整的工作代码:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome()
driver.maximize_window()
wait = WebDriverWait(driver, 10)
driver.get("https://www.motogp.com/es/gp-results/2024/qat/motogp/rac/classification")
# Click on Rechazar button
wait.until(EC.element_to_be_clickable((By.ID, "onetrust-reject-all-handler"))).click()
select_element = wait.until(EC.element_to_be_clickable((By.XPATH, "(//select[@class='primary-filter__filter-select primary-filter__filter-select--cat'])[2]")))
select = Select(select_element)
select.select_by_visible_text("SPR")
time.sleep(20)
结果: