前言
selenium定位一组元素,批量操作循环点击的时候会报错:element is not attached to the page document
实现目标:批量点击标题,获取每个页面的url地址
代码如下:
# coding:utf-8
from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://www.cnblogs.com/canglongdao/")
titles=driver.find_elements_by_xpath("//div[@id='main']/div/h2/a")
for i in titles:
i.click()
print(driver.current_url)
driver.back()
运行结果:
https://www.cnblogs.com/canglongdao/p/13613712.html
Traceback (most recent call last):
File "E:/study/selenium_study/a825.py", line 7, in <module>
i.click()
...
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=84.0.4147.135)
why?
由于第一次点击后,返回页面时,刷新了
页面刷新后元素的属性是没变,但是element的值却变了,所有之前定位的元素element都过期了。
分析问题
1.当页面上有点击时,进入新页面,返回时,会刷新;我们可以分别打印出点击前后的元素
from selenium import webdriver
dr