How to catch network failures while invoking get()

2019-03-07 00:26发布

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this: enter image description here

If I reload the page 99% it will load fine, what is the proper way to handle this ?

MY CODE:

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

I am not getting into TIMEOUT EXCEPTION but to the break part.

1条回答
成全新的幸福
2楼-- · 2019-03-07 00:58

As per your question and your code trials as you are trying to access the url passed through the argument link you can adapt a strategy where:

  • Your program will make pre-defined number of trials to invoke the desired url, which you can pass through range().
  • Once you invoke get(link) your program will invoke WebDriverWait() for a predefined interval for the url to contain a pre-defined partialURL from the url.
  • You can handle this code within a try{} block with ExpectedCondition method titleContains() and in case of TimeoutException invoke browser.get(link) again within the catch{} block.
  • Your modified code block will be:

    #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.titleContains(partialTitle))
            break
        except TimeoutException:
            browser.get(link)
    logger.warning('there is no valid connection')
    
查看更多
登录 后发表回答