无法使用Python中的Selenium从下拉菜单中选择xpath元素

时间:2017-04-30 22:22:26

标签: python selenium xpath drop-down-menu

我很难尝试使用Selenium从下拉菜单中选择元素。

检查页面如下所示:

<select id="numbers" name="numbers" style="display: inline-block;">
<option value="all">all numbers</option>
<option value="c4ca4238a0b923820dcc509a6f75849b">One</option>
<option value="c81e728d9d4c2f636f067f89cc14862c">Two</option>
<option value="34173cb38f07f89ddbebc2ac9128303f">Three</option>
</select>

我使用的代码是:

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="numbers"]/option[3]'))
)

element.click();

但我收到错误:

  EC.element_to_be_clickable((By.XPATH, '//*[@id="numbers"]/option[3]'))
  File "/Library/Python/2.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/7q/ttwklc8j10x_8q7yy8t2scpw0000gn/T/tmpYJKH0R/extensions/fxdriver@googlecode.com/components/driver-component.js:10770)
    at FirefoxDriver.prototype.findElement (file:///var/folders/7q/ttwklc8j10x_8q7yy8t2scpw0000gn/T/tmpYJKH0R/extensions/fxdriver@googlecode.com/components/driver-component.js:10779)
    at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/7q/ttwklc8j10x_8q7yy8t2scpw0000gn/T/tmpYJKH0R/extensions/fxdriver@googlecode.com/components/command-processor.js:12661)
    at DelayedCommand.prototype.executeInternal_ (file:///var/folders/7q/ttwklc8j10x_8q7yy8t2scpw0000gn/T/tmpYJKH0R/extensions/fxdriver@googlecode.com/components/command-processor.js:12666)
    at DelayedCommand.prototype.execute/< (file:///var/folders/7q/ttwklc8j10x_8q7yy8t2scpw0000gn/T/tmpYJKH0R/extensions/fxdriver@googlecode.com/components/command-processor.js:12608)

我能够理解它无法找到xpath,即使我仔细检查了从Chrome复制/粘贴它。

我错过了什么?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

由于您必须从选择控件中选择选项,最好使用Select类,如下所示:

select = Select(driver.find_element_by_id("numbers"))
select.select_by_visible_text("Two")

请告诉我,上述代码是否适合您。

答案 1 :(得分:0)

我认为首先您需要点击该下拉菜单,而不是显示选项。

element = WebDriverWait(driver, 20).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="numbers"]')))
element.click();

而不是点击//option[3]