0

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.

Pittsie
  • 79
  • 11
  • put it in any place in loop and see what will happen. And when you get error message then read it and try to resolve it. Shortly: first try, next check in Google, finally ask question. – furas Mar 05 '20 at 15:47
  • @furas Thank you for that piece of advice, however that is exactly what I am asking for help with. I can't think of how to involve this in the loop – Pittsie Mar 05 '20 at 17:02
  • first simply copy and paste code to loop and run it. And if it will not work then you at least get error message which you can use to search in Google. And then you can also test code in different place or in different order. This way we learn it - by testing code in different configurations. – furas Mar 05 '20 at 17:03
  • BTW: you could add url for page which shows alert and we would have page for testing code. – furas Mar 05 '20 at 17:08
  • Does this answer your question? [Check if any alert exists using selenium with python](https://stackoverflow.com/questions/19003003/check-if-any-alert-exists-using-selenium-with-python) – Greg Burghardt Mar 05 '20 at 17:30
  • @GregBurghardt sadly not as the pages change so I am never using the same url or that would work perfectly – Pittsie Mar 05 '20 at 18:46
  • The answer in that question refers to using a WebDriverWait object in order to wait for an alert to be present, then it accepts the alert. You can always trap the WebDriverTimeout exception for cases where no alert exists. – Greg Burghardt Mar 05 '20 at 19:08
  • what may be the easiest solution is to use the unhandled prompt behavior option in the driver... set it to either accept or dismiss. I believe the default is dismiss and notify which will throw an exception. Also see this thread: https://stackoverflow.com/questions/57700388/how-to-set-unexpectedalertbehaviour-in-selenium-python – pcalkins Mar 05 '20 at 19:48
  • @furas just as an FYI you asking for me to post the url means you did not understand the question. As stated I am feeding the program a list of urls (about 50k of them) I am looking to be able to go through the png files quickly and determine if they are what I need or not so I have no idea what most of them are I just keep crashing for similar errors and want to add error handling where if an error move to next – Pittsie Mar 06 '20 at 14:15
  • to create solution we need some urls which we can use to see problem and test code. But if you have problem with errors then simply use try/except to catch it. – furas Mar 06 '20 at 14:28

1 Answers1

2

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

furas
  • 134,197
  • 12
  • 106
  • 148