我希望我的代码能够处理互联网出现故障一段时间的情况。目前我正在使用带有 TimeoutException 的 try/except 子句,但这不起作用,因为 Chrome 在没有互联网时不会超时,它只返回此页面:
No Internet
Try:
Checking the network cables, modem and router
Reconnecting to Wi-Fi
ERR_INTERNET_DISCONNECTED
由于没有超时,我的代码只是继续搜索元素并且没有发现互联网的丢失。
当 chrome 没有互联网时,是否会引发异常?
代码:
driver = webdriver.Chrome(executable_path=mypath)
driver.implicitly_wait(10)
driver.set_page_load_timeout(10)
try:
driver.get(url)
elem = driver.find_element_by_xpath(xpath).get_attribute("content")
except TimeoutException:
print('TimeoutException')
最佳答案
也许你可以检测是否元素 No Internet
存在
def has_connection(driver):
try:
driver.find_element_by_xpath('//span[@jsselect="heading" and @jsvalues=".innerHTML:msg"]')
return False
except: return True
driver = webdriver.Chrome()
driver.get("https://www.google.com")
if not has_connection(driver):
print('No Internet connection, aborted!')
driver.quit()
exit()
# connection is good continue
elem = driver.find_element_by_xpath(xpath).get_attribute("content")
关于python-3.x - 使用 Python 和 Chromedriver 进行 Internet 异常处理的 Selenium 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53593284/