【问题标题】:Can't select an option无法选择选项
【发布时间】:2016-01-21 23:11:38
【问题描述】:

我有这个 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>

我正在尝试通过在 selenium 中使用 css_selector 和 python 来选择“Team_02”。 为什么会这样:element = driver.find_element_by_css_selector('#stuff &gt; option:nth-child(2)') 而这不是:element = driver.find_element_by_css_selector('#stuff &gt; option[value="Team_02"').click() 关键是我想用第二种方法选择,因为值不断变化。

重要:

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

【问题讨论】:

    标签: python firefox selenium css-selectors webdriver


    【解决方案1】:

    根据您的问题,我知道您想使用 CSS(因为您也可以使用 Xpath 或 Selenium 的 Select-class)

    使用 CSS,您可以通过 value-attribute 进行搜索,但随后您需要询问 value-number

    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()
    

    【讨论】:

    • 不能使用值,因为它总是在变化,而且它现在也可以使用文本,对不起。
    • 也许有一种方法可以将 vaue 插入到这个表达式中: element = driver.find_element_by_css_selector('#stuff > option:nth-child(2)') 使用 child 而不是 "2" 使用 value ?有可能吗?
    • 您的 CSS 选择器中缺少关闭的 ] ......所有三个。我会编辑它,但它没有足够的字符...... :)
    【解决方案2】:

    我建议如下使用selenium.webdriver.support.ui.Select

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

    【讨论】:

    • 我在发布这个问题之前试过这个,也没有用。也可以通过模拟 Enter 键来尝试 .send_keys("\n") ,但这也不起作用。
    【解决方案3】:

    如果想使用 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)
    

    【讨论】:

    • 仍然driver.find_element_by_xpath("//select[@id='stuff']/option[contains(text(),'Team_02')"].click() 不起作用?可以分享更多你认为不敏感的细节吗?
    • 是的,还是不行。关键是我从以前的下拉列表中选择了这个元素 = driver.find_element_by_css_selector('#stuff > option[value="Team_02"').click(),但是对于这个特定的下拉列表它不起作用而且我没有知道为什么。
    • 在该代码行,它说它无法通过该路径找到元素。
    • 页面中是否有多个Team_02 如果没有,那么driver.find_element_by_xpath("//select[@id='stuff']/option[contains(text(),'Team_02')").click() 应该可以工作。不止一个吗?
    • 不是同名的,没有。我知道它应该是因为我在使用 css_selector 时在主帖中编写的方法 2 适用于其他下拉菜单。
    猜你喜欢
    • 2021-12-06
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    相关资源
    最近更新 更多