【问题标题】:Selecting option from dropdown menu using Selenium; Unable to locate element使用 Selenium 从下拉菜单中选择选项;无法定位元素
【发布时间】:2021-07-14 01:09:32
【问题描述】:

我需要从下拉列表中选择一个元素。我正在使用 Selenium,但我很难选择下拉列表本身以从可用选项中进行选择,并不断收到错误消息“消息:没有这样的元素:无法找到元素:”。我尝试了以下方法:

from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait


driver=webdriver.Chrome()
driver.get('mysite.com')
driver.implicitly_wait(10)
driver.find_element_by_xpath('//*[@id="xpath-example"]').click()
select.select_by_visable_text('option 1')

【问题讨论】:

  • 您能否包含有问题的 html 代码并检查它是否在任何 iframe 或影子根下。此外,您从未正确使用过 select。

标签: python selenium xpath webdriver


【解决方案1】:

有几件事:首先,您可能需要返回列表的 find_elements,而不是返回对象的 find 元素。

此外,由于您尝试访问的元素可能会在未知时间变得可见,您可以使用定时等待,这(通过您的代码)将始终等待 10 秒。或者你可以使用 webdriverwait 函数,它只会等到它可见(可以是 2,3 或任何时间直到你定义的超时)

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome()
driver.get('mysite.com')


try:
    elem = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="xpath-example"]')))
    item = elem.select_by_visible_text('option 1')
except:
    print("Couldn't find elem")
    pass

【讨论】:

    【解决方案2】:

    您可以尝试使用 xpath click() 操作吗:

    //*[@id="x"]/option[1]

    类似: driver.find_element_by_xpath('//*[@id="x"]/option[1]').click()

    【讨论】:

      【解决方案3】:
      elem=driver.find_element_by_xpath('//*[@id="xpath-example"]')
      sel = Select(elem)
      
      sel.select_by_index(1)
      sel.select_by_visible_text("option 1")
      

      首先你需要找到elem并把它放到Select中。然后尝试两个选项之一。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-23
        • 2019-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多