使用selenium在联合选择/列表元素中导航

问题描述 投票:0回答:1
python html selenium-webdriver
1个回答
0
投票

如果我正确理解您的目标(选择下拉选项),我建议模拟本机用户行为并依赖可见元素。

下拉元素有选择器

.superstar-search--selection-box
。 您应该等待它出现并单击它。

下拉选项有选择器

.superstar-search--option
。您应该等待此元素的可见性并过滤它们,例如,通过包含文本条件。

您可以通过将下拉打开选择器和下拉选项选择器定义为函数参数来构建比我编写的更复杂的函数。

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.wwe.com/superstars")
wait = WebDriverWait(driver, 15)

def select_dropdown_option_by_text(text):
    dropdown = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.superstar-search--selection-box')))
    dropdown.click()
    options = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '.superstar-search--option')))
    expected_option = [element for element in options if element.text.lower() == text]
    expected_option[0].click()

select_dropdown_option_by_text('all superstars')
© www.soinside.com 2019 - 2024. All rights reserved.