[英]Selenium - How to select item from div drop down list?
I am trying to select the second option from the div drop down via python/selenium.我正在尝试通过 python/selenium 从 div 下拉列表中选择第二个选项。 The code below is what I have so far.下面的代码是我到目前为止所拥有的。 The first line opens the drop down and works.第一行打开下拉菜单并开始工作。 The second line attempts to select the 2 option and click it.第二行尝试选择 2 选项并单击它。 I have tried "2", "22", and "Option-22" but none seem to work.我已经尝试过“2”、“22”和“Option-22”,但似乎都不起作用。
Sample Python Selenium Code示例 Python Selenium 代码
#opens drop down
browser.find_element(By.XPATH,".//*[@id='Account']").click()
#selects item from dropdown
browser.find_element(By.XPATH,".//*[@id='Account']/option[22]").click()
Error Message:错误信息:
Message: invalid selector: Unable to locate an element with the xpath expression .//*[@id='Account']/option[22] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string './/*[@id='Account']/option[22]' is not a valid XPath expression.
Sample HTML Code:示例 HTML 代码:
<div id="Account" class="">
<select>
<option selected="" value="11">Option-11</option>
<option value="22">Option-22</option>
<option value="33">Option-33</option>
</select>
</div>
The XPath you want is:您想要的 XPath 是:
"//*[@id='Account']//option[@value='22']"
Or you can use the following CSS Selector:或者您可以使用以下 CSS 选择器:
'#Account option[value="22"]'
Or with SeleniumBase , you can do the full select option in one line:或者使用SeleniumBase ,您可以在一行中执行完整的选择选项:
self.select_option_by_text("#Account select", "Option-22")
(Full disclosure: I maintain SeleniumBase) (完全披露:我维护 SeleniumBase)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.