简体   繁体   中英

Handle alert in Selenium Python

I have the following pop-up alert that I want to handle after a file upload. I have used the code below and it throws the error below.

在此处输入图片说明

wait.until(EC.alert_is_present())
driver.switch_to.alert().accept()

Traceback (most recent call last): File "update.py", line 45, in driver.switch_to.alert().accept() TypeError: 'Alert' object is not callable

Why is this happening? I have handled a similar alert (that one had a cancel button?) in this manner.

There are two ways to accept alert available in Python + selenium (there is also JavaScript code for execute_script() , but it's not related to current issue):

driver.switch_to_alert().accept() # deprecated, but still works
driver.switch_to.alert.accept()

Note that in second line you don't need to call alert() as you did in your code

Problem with alert boxes (especially sweet-alerts is that they have a delay and Selenium is pretty much too fast)

An Option that worked for me is:

while True:
    try:
        driver.find_element_by_xpath('//div[@class="sweet-alert showSweetAlert visible"]')
        break
    except:
        wait = WebDriverWait(driver, 1000)

confirm_button = driver.find_element_by_xpath('//button[@class="confirm"]')
confirm_button.click()

Another option to handle alerts in Selenium Python would be to eliminate the notifications all together, if they are not needed.

You can pass in options to your webdriver browser that disables the notifications.

Example Python code using Chrome as the browser with options:

from selenium import webdriver 
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-notifications")
driver = webdriver.Chrome(ChromeDriverManager().install(),options=chrome_options) 

driver.get('https://google.com')
print("opened Google")
driver.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM