Pittsie
Pittsie

Reputation: 79

Selenium Alert Handling Python

So I am using Selenium to simply go to a given list of websites and take a screenshot of them. However I have run into some having alerts and some do not. I am looking to do something along the lines of if alert then this else keep moving.

Here is my current code

from selenium import webdriver
import pandas as pd
import time

path = "C:/Users/dge/Desktop/Database/NewPythonProject/html Grabber/Output/Pics/"
df = pd.DataFrame()
df = df.append(pd.read_csv('crime.csv'), ignore_index=True)
driver = webdriver.Chrome('C:/Users/dge/Desktop/Database/NewPythonProject/html Grabber/chromedriver.exe')

for i in df.index:
    print(i)
    pic = path + df['site'][i] + '.png'
    driver.get('http://' + df['site'][i])
    time.sleep(5)
    driver.save_screenshot(pic)

I've seen this but just not sure how to add it in the loop

driver.find_element_by_id('').click()
alert = driver.switch_to_alert()

The best way to put this may be to say ignore any errors and continue on through my list of urls.

Upvotes: 0

Views: 298

Answers (1)

furas
furas

Reputation: 143097

JavaScript can create alert(), confirm() or prompt()

To press button OK

driver.switch_to.alert.accept()  # press OK

To press button CANCEL (which exists only in confirm() and prompt())

driver.switch_to.alert.dismiss()  # press CANCEL

To put some text in prompt() before accepting it

prompt = driver.switch_to.alert
prompt.send_keys('foo bar')
prompt.accept()

There is no function to check if alert is displayed
but you can put it in try/except to catch error when there is no alert.

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

Minimal working example.

Because I don't know page which displays alert so I use execute_script to display it.

from selenium import webdriver
import time

#driver = webdriver.Firefox()
driver = webdriver.Chrome()

driver.get('http://google.com')

# --- test when there is alert ---

driver.execute_script("console.log('alert: ' + alert('Hello World!'))")
#driver.execute_script("console.log('alert: ' + confirm('Hello World!'))")
#driver.execute_script("console.log('alert: ' + prompt('Hello World!'))")
time.sleep(2)

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

# --- test when there is no alert ---

try:
    driver.switch_to.alert.accept()  # press OK
    #driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)

# ---

driver.save_screenshot('image.png')
driver.close()

BTW: if you want to first try to press CANCEL and when it doesn't work then press OK

try:
    driver.switch_to.alert.dismiss()  # press CANCEL
except Exception as ex:
    print('Exception:', ex)
    try:
        driver.switch_to.alert.accept()   # press OK
    except Exception as ex:
        print('Exception:', ex)

BTW: different problem can be popup notifications or geolocation alerts

How to click Allow on Show Notifications popup using Selenium Webdriver

Upvotes: 2

Related Questions