Home > Mobile >  Handle Alert with Python and Selenium
Handle Alert with Python and Selenium

Time:03-20

I'm trying to write Login credentials using send_keys element method with Selenium on this alert: Login Alert

I get this alert after clicking on a button in a new window but I can't inspect the elements on this window.

here is my code

import time
import pynput
from selenium import webdriver

driver=webdriver.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
driver.get("http://10.15.44.177/control/userimage.html")
time.sleep(3)
window_before = driver.window_handles[0]
driver.maximize_window()
btn=driver.find_element_by_name("TheFormButton3")
btn.click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
obj = driver.switch_to.alert
time.sleep(2)
obj.send_keys('Admin')
time.sleep(2)

I get this error that tells me that there is no alert

CodePudding user response:

I can't acess to the page so I can't try my code but, first I optimized It by adding WebdriverWait and the new By. function:

from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = wd.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
wait = WebDriverWait(driver, 15)

driver.get("http://10.15.44.177/control/userimage.html")
driver.maximize_window()
window_before = driver.window_handles[0]
wait.until(EC.element_to_be_clickable((By.NAME, "TheFormButton3"))).click()
driver.switch_to.window(driver.window_handles[1])

alert = driver.switch_to.alert
alert.send_keys('Admin\npassword\n') # \n works as an ENTER key

You can try this code to see if the alert really exists or is an element of the webpage:

from selenium.common.exceptions import NoSuchElementException

def is_alert_present(self):
    try:
        self.driver.switch_to_alert().send_keys('Admin\npassword\n') # \n works as an ENTER key
        print('Sucess')
    except NoSuchElementException:
        print('No Alert Present')

Also see Alerts in the Selenium Documentation

Also Try:

parent_h = browser.current_window_handle
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back

CodePudding user response:

So finally I've found a solution..I used the approach where you have to send username and password in URL Request and it worked:

http://username:[email protected]
  • Related