NoSuchElementException:消息:没有这样的元素:在尝试选择下拉框中的选项时无法找到元素

时间:2019-01-14 08:51:56

标签: python selenium selenium-webdriver xpath webdriverwait

我正在尝试创建一个脚本,该脚本可以自动单击下拉框并单击我想要的选项。我曾尝试从另一个类似的问题实现代码,但是却收到错误消息。

使用类似问题的解决方案,我尝试了以下代码行:

driver.find_element_by_xpath("//select[@name='interface']/option[text()='Management']").click()

HTML

<select class="col-1 custom-select" name="interface" id="interface" required="required">
  <option selected="" disabled="" class="hideoption">Select Interface</option>
  <option value="InterfaceLAN">Production</option>
  <option value="MgmtLAN">Management</option>
  <option value="Clustering">Clustering</option>
</select>

我想自动化单击下拉框并选择“管理”选项的过程。但是,我收到一条错误消息,如下所示:

NoSuchElementException: Message: no such element: Unable to locate element:"method":"xpath","selector":"//select[@name='interface']/option[text()='Management']"}

2 个答案:

答案 0 :(得分:2)

由于所需元素是select元素,因此您需要使用Select类并诱导 WebDriverwait 以使所需元素可见您可以使用以下解决方案:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
select = Select(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//select[@id='interface' and @name='interface']"))))
select.select_by_value("MgmtLAN")

答案 1 :(得分:1)

尝试使用Select Class,在那里提供下拉菜单的xpath。 然后尝试通过值,索引或可见文本选择下拉列表

代码:

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_name('name'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)
相关问题