不能select一个选项

Can't select an option

我有这个html代码

<select id="stuff" name="stuff_name">
<option value="10002">Team_01</option>
<option value="10001">Team_02</option>
<option value="10000">Team_03</option>
<option value="0">[default]</option></select>

我正在尝试 select“Team_02”,方法是在带有 python 的硒中使用 css_selector。 为什么这样有效:element = driver.find_element_by_css_selector('#stuff > option:nth-child(2)') 而这不是:element = driver.find_element_by_css_selector('#stuff > option[value="Team_02"').click() 关键是我想用第二种方法select,因为值不断变化。

重要:

不能使用值,因为它总是在变化

根据你的问题,我了解到你想使用 CSS(因为你也可以使用 Xpath 或 Selenium 的 Select-class)

使用 CSS 您可以通过值属性进行搜索,但是您需要询问值编号

driver.find_element_by_css_selector('#stuff > option[value="10001"]').click()

或者您通过文本搜索:

driver.find_element_by_css_selector('#stuff > option[text="Team_02"]').click()

另一种方式是内文

driver.find_element_by_css_selector('#stuff > option[innertext="Team_02"]').click()

想用xpath试试

driver.find_element_by_xpath("//select[@id='stuff']/option[contains(text(),'Team_02')").click()

或者你可以试试蛮力。

for option1 in driver.find_elements_by_xpath("//select[@id='stuff']/option"):
    if option1.text == 'Team_02':
        option1.click()
        time.sleep(100)

我建议使用 selenium.webdriver.support.ui.Select,如下所示。

select = Select(driver.find_element_by_id("stuff"))
select.select_by_visible_text("Team_02")