selenium报错:element is not attached to the page document

在这里插入图片描述

def testpatentDetail_40(self, patentDetialPage, db, driver):
    patentDetialPage.click_menu3()
    totalpage = patentDetialPage.get_totalpage()
    for i in range(0, int(totalpage)):
        patentDetialPage.click_pagenum(i + 1)
        # driver.implicitly_wait(30)
        # time.sleep(1)
        for n in range(0, patentDetialPage.get_discusslistlen()):
            sql = 'sqlstr'
            con = db.getOne(db.executeSql(sql))
            # 评论人头像
            if con[8] is None:
                pytest.assume(patentDetialPage.get_discussimg(n) == '')
            else:
                pytest.assume(patentDetialPage.get_discussimg(n) == str(con[8]))
			# 评论人+评论内容
            content = str(con[7]) + ':' + con[5]
            pytest.assume(patentDetialPage.get_discusscontent(n).replace(" ", "") == content.replace(" ", ""))
			# 评论时间
            newdate = str(con[6]).rpartition(':')[0]
            pytest.assume(patentDetialPage.get_discusstime(n) == str(newdate))

遍历翻页功能测试时,出现报错:
Message: element is not attached to the page document

官方给出解释如下:
The element has been deleted entirely.
The element is no longer attached to the DOM.

检查发现点击翻页会调用ajax请求,在请求未完成时,评论列表元素过期,无法获取到元素

最开始想着加个等待时间WebDriverWait就好了(封装方法里都包含显示等待),看来是我太天真,最后想明白了其实在操作点击页码之后,ajax没有立即加载完成,所以此时元素还是存在的,但ajax响应后,元素就过期了,原因是点击页码操作首先响应ajax请求,ajax请求响应成功后元素过期,下面三个请求响应元素再次出现。
在这里插入图片描述
然后试着强等 time.sleep(1),发现不报错了,不过这种方式不稳定,万一网络不好或者服务器压力过大,等一秒也不够啊,那等30秒,每次都等30秒么?那也不现实,那就没有其他方法类似于WebDriverWait么?

于是我换种方式,能不能获取浏览器所有请求呢,通过各种百度,找到了Selenium拦截页面Ajax请求及响应数据的方法(参考:https://www.likeinlove.com/info/104.html)

修改代码如下,妥妥的解决了,哈哈:

# conftest.py
@pytest.fixture(scope="session", name="server")
def ser():
    server = Server(os.getcwd() + r'\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat')
    server.start()
    yield server
    server.stop()

@pytest.fixture(scope="session", name="proxy")
def proxy(server):
    proxy = server.create_proxy()
    return proxy

# 可视化打开浏览器
@pytest.fixture(scope="session", name="driver")
def browser(proxy):
    chrome_options = Options()
    chrome_options.add_argument(f'--proxy-server={proxy.proxy}')
    chrome_options.add_argument('--ignore-certificate-errors')  # 忽略不安全证书提示
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.maximize_window()
    yield driver
    # quit是退出浏览器
    driver.quit()
def testpatentDetail_40(self, patentDetialPage, db, proxy):
    proxy.new_har(options={'captureHeaders': True, 'captureContent': True})
    patentDetialPage.open('https://')
    patentDetialPage.click_menu3()
    totalpage = patentDetialPage.get_totalpage()
    for i in range(0, int(totalpage)):
        patentDetialPage.click_pagenum(i + 1)
        att = 1
        while 1:
            if att == 1:
                result = proxy.har
                for entry in result['log']['entries']:
                    url = entry['request']['url']
                    if "https://" in url:
                        response = entry['response']  # 响应对象
                        content = response['content']  # 响应内容对象
                        text = content['text']  # 响应内容
                        if text is not None:
                            att = 0
                            break
                        else:
                            time.sleep(0.1)
                        break
                    else:
                        time.sleep(0.1)
            else:
                break
        for n in range(0, patentDetialPage.get_discusslistlen()):
            sql = 'sqlstr'
            con = db.getOne(db.executeSql(sql))
            # 评论人头像
            if con[8] is None:
                pytest.assume(patentDetialPage.get_discussimg(n) == '')
            else:
                pytest.assume(patentDetialPage.get_discussimg(n) == str(con[8]))
			# 评论人+评论内容
            content = str(con[7]) + ':' + con[5]
            pytest.assume(patentDetialPage.get_discusscontent(n).replace(" ", "") == content.replace(" ", ""))
			# 评论时间
            newdate = str(con[6]).rpartition(':')[0]
            pytest.assume(patentDetialPage.get_discusstime(n) == str(newdate))
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值