我试图通过python/selenium从div下拉选择第二个选项。下面的代码是我目前所拥有的。第一行打开下拉菜单并工作。第二行尝试选择2选项并单击它。我试过"2", "22"one_answers"Option-22"但似乎都不奏效。
示例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()
错误信息:
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.
示例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>
您想要的XPath是:
"//*[@id='Account']//option[@value='22']"
或者你可以使用下面的CSS选择器:
'#Account option[value="22"]'
或者使用SeleniumBase,您可以在一行中完成完整的选择选项:
self.select_option_by_text("#Account select", "Option-22")
(充分披露:我维护SeleniumBase)