5

I want my code to be able to handle circumstances when the internet goes down for a period. Currently I'm doing it using a try/except clause with a TimeoutException but that isn't working as Chrome doesn't Timeout when there is no internet, it just returns this page:

No Internet

Try:

  • Checking the network cables, modem and router

  • Reconnecting to Wi-Fi

ERR_INTERNET_DISCONNECTED

Since there's no timeout, my code just continues searching for elements and the loss of internet is not caught.

Is there anyway of raising an exception when there is no internet in chrome?


Code:

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')
Adafe Jaja
  • 53
  • 1
  • 5

2 Answers2

2

maybe you can just detect if element No Internet exist

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")
ewwink
  • 18,382
  • 2
  • 44
  • 54
  • 2
    Thanks a lot, I can see that could be a useful workaround - but wouldn't that be dependent on Google Chrome keeping that page format for those instances when there is no internet connection? I'm trying to make the code as robust as possible, so I was hesitant to test for elements on the no internet page. – Adafe Jaja Dec 03 '18 at 12:50
  • it just the easiest way and there are more but selenium itself has no option or function to detect if connection is down. – ewwink Dec 03 '18 at 13:43
0

It´s late but, you can use

except exceptionType:
    try:
        driver.find_element(By.XPATH,'//body[@class="neterror"]')
        print('Yes, the internet is down')
    except:
        print('No, the internet is ok')
Xavier
  • 26
  • 3