0

I have a bot that I'm testing and it works for the most part, but every once in a while when it navigates to a new page, Chrome throws a "Reload Page?" alert and it stops the bot. How can I add a check in the bot to look for this alert, and if it's there click the "Reload" button on the alert?

In my code I have

options.add_argument("--disable-popup-blocking")

and

driver = webdriver.Chrome(chrome_options=options, executable_path="chromedriver.exe")

but it still happens every once in a while. Any advice?

  • Use [this](https://stackoverflow.com/questions/19003003/check-if-any-alert-exists-using-selenium-with-python) to check if there's an alert. And [this](https://stackoverflow.com/questions/42005956/handle-alert-in-selenium-python) to handle it. – RafalS Dec 09 '19 at 18:01

1 Answers1

1

You can use driver.switch_to_alert to handle this case.

I would also invoke WebDriverWait on the alert itself, to avoid the NoSuchAlert exception:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

def refresh_with_alert(driver):

    # wrap this in try / except so the whole code does not fail if alert is not present
    try: 
        # attempt to refresh
        driver.refresh()

        # wait until alert is present
        WebDriverWait(driver, 5).until(EC.alert_is_present())

        # switch to alert and accept it
        driver.switch_to.alert.accept()

    except TimeoutException:
        print("No alert was present.")

Now, you can call like this:

# refreshes the page and handles refresh alert if it appears
refresh_with_alert(driver)

The above code will wait up to 5 seconds to check if an alert is present -- this can be shortened based on your code needs. If the alert is not present, the TimeoutException will be hit in the except block. We simply print a statement that the alert does not exist, and the code will move on without failing.

If the alert is present, then the code will accept the alert to close it out.

CEH
  • 5,701
  • 2
  • 16
  • 40