栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.4binbrowsermob-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))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/740464.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号