最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handle alert in Selenium Python - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Feb 2, 2017 at 15:19 CovCov 5821 gold badge5 silver badges21 bronze badges 1
  • 1 Possible duplicate of stackoverflow./questions/25605018/… – Arount Commented Feb 2, 2017 at 16:40
Add a ment  | 

3 Answers 3

Reset to default 3

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.')
print("opened Google")
driver.quit()
发布评论

评论列表(0)

  1. 暂无评论