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

时间:2018-03-28 23:02:28

标签: python google-chrome selenium selenium-webdriver webdriver

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

1 个答案:

答案 0 :(得分:0)

错误说明了一切:

@if(!empty($products)
   @foreach ($products as $product)
      @if(isset($product->name) && $product->name =="")
           {{$product->name}}
       @else
         No record   
      @endif              

   @endforeach
@else
    No record Found....
@endif

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document 循环中的程序中,您正在页面上找到for()标记元素,文本为&gt;&gt; 并调用<a>和由于click()事件, HTML DOM 发生了变化。当您的程序第二次迭代click()循环时,标识为for() WebElement 可能无法加载,但 Selenium 会尝试引用上一次迭代中已经转为陈旧的搜索。因此,您会看到 StaleElementReferenceException

解决方案

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

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

对于 WebElement ,您可以将WebDriverWaitexpected_conditions子句一起设置为element_to_be_clickable子句,并使用特定的页码 (例如 3 4 5 等)可点击,如下所示:

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