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.