Selenium:陈旧元素引用:元素未附加到Python中的页面文档

时间:2016-11-28 10:24:12

标签: python selenium dom

我使用Python的Selenium版本来迭代Select元素选项。它在网站上运行良好,但在另一个网站上运行失败,错误:Message: stale element reference: element is not attached to the page document我当然查了一下,但我找到的答案对我来说并没有成功。我使用time.sleep()等待页面加载,我可以看到它正在浏览器中加载。我不知道该怎么办。

它在代码中的外观:

options = Select(driver.find_element_by_xpath("my_element's_xpath")).options
for option in options:
    option.click()
    sleep(5)

首先运行它工作正常,第二次运行我得到错误。

以下是Chromium中Dev Tools中的Select元素: screenshot 我相信它可能必须使用第一个选择选项,但周围没有<option>标记,但我不确定如何从DOM中删除它。

2 个答案:

答案 0 :(得分:0)

我程序中的代码比我所展示的要大一些,正如J0HN指出的那样,它导致浏览器刷新。我在一种黑客中解决了它,将每个选项值存储在引用列表中,然后迭代它。代码说得比文字好,所以请看下面的内容:

for option in options:
    options_reference.append(option.text)

for option in options_reference:
    option_element = driver.find_element_by_xpath(
            "//*[contains(text(), '" + option + "')]")
    option_element.click()

可以通过仅将XPath缩小到选项标记来进一步改进。

答案 1 :(得分:0)

就我而言,在sleep(2)

之前添加from time import sleep(取自options = Select(...))就足够了