python - 如何在通过 Selenium 和 Python 调用 get() 方法时捕获网络故障?
问题描述
我正在使用带有 selenium 的 Chrome,并且测试运行良好,直到突然互联网/代理连接断开,然后 browser.get(url) 得到我这个:
如果我重新加载页面 99% 它将加载正常,处理此问题的正确方法是什么?
我的代码:
def web_adress_navigator(browser, link):
"""Checks and compares current URL of web page and the URL to be navigated and if it is different, it does navigate"""
try:
current_url = browser.current_url
except WebDriverException:
try:
current_url = browser.execute_script("return window.location.href")
except WebDriverException:
current_url = None
if current_url is None or current_url != link:
retries = 5
while retries > 0:
try:
browser.get(link)
break
except TimeoutException:
logger.warning('TimeoutException when tring to reach page')
retries -= 1
while not is_connected():
sleep(60)
logger.warning('there is no valid connection')
我没有进入 TIMEOUT EXCEPTION 而是进入休息部分。
解决方案
根据您的问题和代码试验,当您尝试访问通过参数传递的urllink
时,您可以采用以下策略:
- 您的程序将进行预定义的试验次数来调用您可以通过的所需url
range()
。 - 一旦你调用
get(link)
你的程序将调用WebDriverWait为一个预定义的时间间隔url 包含一个预定义partialURL
的url。 - 您可以使用expected_conditions方法title_contains()
try{}
在块内处理此代码,以防在块内再次调用。TimeoutException
browser.get(link)
catch{}
您修改后的代码块将是:
#imports from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException # other code works browser.get(link) for i in range(3): try: WebDriverWait(browser, 10).until(EC.title_contains(partialTitle)) break except TimeoutException: browser.get(link) logger.warning('there is no valid connection')
推荐阅读
- ansible - 在ansible中一个接一个地执行整个yaml任务文件
- php - 如果 [在 php 中] 为空,如何从检索中跳过图像字段?
- reactjs - 如何从 withHandlers 调用另一个函数?
- angular - 如何在重新加载时在组件之间保留共享服务数据
- python - 在 Spyder 中运行 Vpython 时出错(NameError: name 'gsprint' is not defined)
- sql - Excel 公式到 SQL
- java - 构建 SNAPSHOT 时不会触发 Jenkins Multibranch 项目
- html - 通过链接文本抓取网页
- python-2.7 - 在通过 init 脚本启动的 python 脚本中,无法通过 os.system('scp (...)') 下载文件
- c# - 跟踪侦听器未生成日志文件