Selenium3+python3自动化(四十二)--批量操作循环点击报错

前言

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值