Selenium 单击一次,但下次单击返回 StaleElementReferenceException

2024-01-11

import sys
import urllib2
import time
from bs4 import BeautifulSoup
from selenium import webdriver
import string
import re

reload(sys)
sys.setdefaultencoding('utf8')

baseUrl = 'https://www.breastsurgeons.org/new_layout/membership/membersearch/index.php'

driver = webdriver.Chrome('/usr/local/Cellar/chromedriver/2.36/bin/chromedriver')
driver.get(baseUrl)
time.sleep(20)

for p in range(1,282):

    driver.find_element_by_xpath("//a[contains(text(),'>>')]").click()
    time.sleep(2)

driver.quit()

打开 baseUrl 后,我手动单击“同意”,然后搜索要显示的医生列表。我想翻阅清单。现在,Selenium 仅通过找到“>>”来第一次单击。之后它停止并给出以下错误。

   driver.find_element_by_xpath("//a[contains(text(),'>>')]").click()


  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 80, in click


    self._execute(Command.CLICK_ELEMENT)


  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 628, in _execute


    return self._parent.execute(command, params)


  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 312, in execute


    self.error_handler.check_response(response)


  File "/Library/Python/2.7/site-packages/selenium-3.11.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 242, in check_response


    raise exception_class(message, screen, stacktrace)


selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

该错误说明了一切:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

在你的程序中for()循环你正在定位<a>标签元素的文本为>>在页面上并调用click()并且由于click()事件HTML DOM变化。当你的程序迭代时for()第二次循环也许网页元素确定为driver.find_element_by_xpath("//a[contains(text(),'>>')]")没有加载但是Selenium尝试引用已经转向的上一次迭代中的搜索stale。因此你看到陈旧元素引用异常.

Solution

迭代页面的一种令人信服的方法是:

driver.find_element_by_xpath("//a[contains(text(),'>>')]").click()

你可以诱导WebDriver等待 https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.wait.html#module-selenium.webdriver.support.wait和这个结合预期条件 https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#module-selenium.webdriver.support.expected_conditions子句设置为元素可点击 https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.element_to_be_clickable为了网页元素与特定的页码 (e.g. 3, 4, 5等)是可点击的如下 :

WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(text(),'3')]"))).click()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Selenium 单击一次,但下次单击返回 StaleElementReferenceException 的相关文章

随机推荐