I am very new to Selenium and am trying to automate sending messages through WhatsApp Web through Google Chrome. I am using a different api which lets users write messages directly to the phone number specified: https://wa.me/. However, there is an alert box which pops up and my code is unable to accept it.
Alert box screenshot
I have tried
driver.switch_to_alert().accept()
but this is resulted in a deprecation warning, so switched to:
alert_box = driver.switch_to.alert
alert_box.accept()
Both result in the following error:
Exception has occurred: NoAlertPresentException
Message: no such alert
(Session info: chrome=105.0.5195.102)
File "<hidden>", line 30, in <module>
driver.switch_to.alert.accept()
Current code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
# Ensure you are logged in to whatsapp web
num = "xxxxxxxxxxxxxxxxxxxxx" # hid the number
driver.get("https://wa.me/" + num)
# Allow time to load page
driver.implicitly_wait(3)
# Switch to alert window to accept the alert to open URL
driver.switch_to.alert.accept()
driver.find_element(By.XPATH, './/a[@class="_9vcv _advm _9scb"][@id="action-button"][@title="Share on WhatsApp"]').click()
# Switch to alert window to accept the alert to open URL
driver.switch_to_alert().accept()
driver.find_element(By.XPATH, '//*[@id="fallback_block"]/div/div/h4[2]/a').click()
Interestingly, no alert shows up if I manually go through the screens myself.
Thanks in advance!
You probably should add some code to wait for the alert to open. Have a look a the following snipped.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
try:
wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present(), 'waiting for alert')
alert = driver.switch_to.alert
alert.accept()
except TimeoutException:
print("timed out waiting for alert")