Python陈旧元素参考:元素未附加到页面文档

时间:2017-06-07 22:58:13

标签: python selenium

无法绕过Stale Element参考。我认为innerArticles数组是错误的,因为它控制整个for循环。在我明确刷新后,我得到过时的元素异常。

基本上我希望页面保持刷新,直到SubItems xpath中的'Text'出现在页面上。由于我不知道何时会发生这种情况,我需要开始并继续重装。

感谢任何帮助。

代码:

innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for links in innerArticles:
    print('inFor')

    SubItems = links.find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = links.find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()

1 个答案:

答案 0 :(得分:0)

当您进行显式刷新时,链接对象将不再有效并将抛出StaleElementReferenceException。刷新后应该再次获取该元素。您可以尝试以下内容:

innerArticles = driver.find_elements_by_xpath("//div[@class='inner-article']")

for i in range(len(innerArticles)):
    print('inFor')

    SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")

    iterator = 0
    if len(SubItems) < 1:
        print('Sub < 1')
        while iterator < 5:
            print('While', iterator)

            time.sleep(1)  # sleep 1 seconds to refresh again
            iterator = iterator + 1  # iterate
            driver.refresh()  # refresh
            SubItems = driver.find_elements_by_xpath("//div[@class='inner-article']")[i].find_elements_by_xpath("//a[text()='Text']")
            break
            if len(SubItems) > 0:
                print('break')
                break

    if len(SubItems) > 0:
        print('SecondIf')
        links = driver.find_elements_by_xpath("//div[@class='inner-article']")[i]
        if links.text.startswith('SText') and links.text.endswith('SText'):
            links.click()