我希望我的代码能够处理一段时间的互联网故障。目前,我正在使用带有TimeoutException的try/except子句来执行此操作,但这无法正常工作,因为在没有互联网的情况下Chrome不会超时,它只会返回以下页面:



由于没有超时,因此我的代码仅继续搜索元素,并且不会发现互联网丢失的情况。

无论如何,如果没有chrome浏览器,是否有引发异常(exception)的情况?

代码:

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")

10-06 09:14