【问题标题】:Using selenium (python) to select an option from a conditional dropdown使用 selenium (python) 从条件下拉列表中选择一个选项
【发布时间】:2016-01-29 01:54:23
【问题描述】:

我正在尝试自动化一些工作中的管理任务,因此我使用 selenium 来操作我们的项目管理平台 (quickbase)。

我填充的第一个项目是一个选择/选项下拉列表,我可以使用 xpath 选择器选择一条记录:

driver.find_element_by_xpath("//select[@id='_fid_67']/option[@value='28']").click()

这很好用。我需要填充的下一个项目也是一个选择/选项下拉菜单。可用选项由第一个选择的选项查询。在萤火虫中,看起来他们正在调用该函数来查询单击第二个下拉菜单的结果。所以接下来我试着点击选择元素 id,它应该调用函数来查询选项。然后我让它等待(尝试了长达 10 秒),然后选择选项。

# click the select element to call function
driver.find_element_by_xpath("//select[@id='_fid_74']").click()

# wait for the query function to finish
driver.implicitly_wait(2)

# select the option
driver.find_element_by_xpath("//select[@id='_fid_74']/option[@value='142']").click()

这给了我两个错误之一:

Element not found in the cache - perhaps the page has changed since it was looked up

File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 107, in check_response
    message = value["value"]["message"]
TypeError: string indices must be integers

我还尝试返回元素列表,遍历它们并检查值是否为“142”,如果是,请单击该元素对象。这也给了我一个错误。我试过使用 xpath: //select[@id='_fid_74']/option[text()='the text'] 这也不起作用。

我认为它与条件选择有关,因为相同的查询适用于第一个下拉列表(第一个代码块)。

有人有什么建议吗?

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    首先,您应该使用Select class 来处理select,它的选项非常简单,并抽象出复杂性:

    from selenium.webdriver.support.select import Select
    
    select = Select(driver.find_element_by_xpath("//select[@id='_fid_74']"))
    select.select_by_value("142")
    

    字符串索引必须是整数

    这是 selenium 2.49 中的 known issue。目前,您需要降级到 2.48:

    pip install selenium==2.48 
    

    【讨论】:

      【解决方案2】:

      使用显式等待代替隐式等待,如下所示:

      from selenium.webdriver.support import expected_conditions as EC
      
      wait = WebDriverWait(driver, 10)
      element=wait.until(EC.element_to_be_selected((driver.find_element_by_xpath("//select[@id='_fid_74']/option[@value='142']"))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-26
        • 2021-06-11
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        相关资源
        最近更新 更多