前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python+selenium自动化:页面加载慢、超时加载情况下内容已经加载完毕的快速执行脚本解决方案,页面加载时间过长优化方案

Python+selenium自动化:页面加载慢、超时加载情况下内容已经加载完毕的快速执行脚本解决方案,页面加载时间过长优化方案

作者头像
小蓝枣
发布2021-12-01 12:11:09
2K0
发布2021-12-01 12:11:09
举报
文章被收录于专栏:CSDN博客专家-小蓝枣的博客

driver.set_page_load_timeout(3) 页面加载时间设置 3 秒,执行到某一步涉及页面加载如果加载时间超过 3 秒就会停止加载并抛出异常,其实这个时候页面内的元素已经加载出来了,我们在这一步进行异常捕获不让程序停止,然后直接执行下一步即可。

报错信息如下: selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 3.000

代码语言:javascript
复制
def analyze_jira(driver, d):
    # 方案一:异常捕获方案
    # 页面加载时间设置,超时会直接报错,将会报错的地方加个异常不过,完美解决问题
    driver.set_page_load_timeout(3)
    
    for (k,v) in d.items():
        driver.find_element_by_xpath('//input[@id="quickSearchInput"]').send_keys(k[4:])
        try:
        	# 查询操作,耗时很长
            ActionChains(driver).send_keys(Keys.ENTER).perform()
        except Exception as e:
            print("抓到异常,页面停止加载,但是程序不停止。")
        time.sleep(1)
        # 提取页面指定元素的文本
        question_zhuti = driver.find_element_by_xpath('//*[@id="summary-val"]').text;

还可以通过 set_script_timeout() 方法来解决问题。

代码语言:javascript
复制
def analyze_jira(driver, d):
    # 方案二:同时设置脚本执行超时时间方案
    # 设置脚本报错之前的等待时间,这个小于等于上面set_page_load_timeout()设置的时间就不会抛错。
    driver.set_page_load_timeout(3)
    driver.set_script_timeout(3)
    
    for (k,v) in d.items():
        driver.find_element_by_xpath('//input[@id="quickSearchInput"]').send_keys(k[4:])
        # 查询操作,耗时很长
        ActionChains(driver).send_keys(Keys.ENTER).perform()
        time.sleep(1)
        # 提取页面指定元素的文本
        question_zhuti = driver.find_element_by_xpath('//*[@id="summary-val"]').text;

set_page_load_timeout() 方法说明: Set the amount of time to wait for a page load to complete before throwing an error. 翻译: 设置在抛出错误之前等待页面加载完成的时间。

set_script_timeout() 方法说明: Set the amount of time that the script should wait during an execute_async_script call before throwing an error. 翻译: 设置脚本在execute_async_script调用期间抛出错误之前应该等待的时间。

喜欢的点个赞❤吧!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档