Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click on a button within a pop-up window with python selenium?

I have a question about click button on a pop-up window. The GUI as below: GUI

HTML content as below: HTML

I'm trying to use python selenium to click the "OK" button in many ways: For example:

driver.switch_to_alert()
driver.find_element_by_id("YesBtn").click()

or

driver.switch_to_alert()
driver.find_element_by_xpath("//div[@id='YesBtn']").click()

or

driver.switch_to_alert()
driver.find_element_by_xpath("//input[@id='YesBtn']/html/body/div/div/div/div/div[3]").click()

But I always get error message like:

Unable to locate element: {"method":"id","selector":"YesBtn"}

Is there anyone can help me to correct the code? Many thanks.

like image 327
dnisqa2 delta Avatar asked Mar 06 '23 14:03

dnisqa2 delta


2 Answers

As per the HTML you have shared it's not an Alert but a Modal Dialog Box. To click on the element with text as OK you have to induce WebDriverWait in-conjunction with expected_conditions clause set to element_to_be_clickable as follows :

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='btn btn-primary' and @id='YesBtn']"))).click()
like image 67
undetected Selenium Avatar answered Mar 09 '23 02:03

undetected Selenium


alert = driver.switch_to_alert()
alert.accept()

This will return the currently open alert object. With this object, you can now accept, dismiss, read its contents or even type into a prompt.

like image 28
Akash Chavan Avatar answered Mar 09 '23 03:03

Akash Chavan