Reputation: 13
I'm trying to return True or False from this javascript method "confirm()" to my python variable. However, it displays the prompt, and the program control moves ahead and never returns anything. How do I stop it from doing so? Is there any other method I can use to take "Yes" or "No" from the user and return it to my python variable? I have tried prompt() but I don't want the user to type anything. I want it to be just a simple "Yes" or "No".
choice= self.driver.execute_script(""" if(confirm('Yes or No?')) {
return true;
}
else{
return false;
} """)
if choice == True:
print('Success!')
else:
print('Failed')
Upvotes: 0
Views: 1633
Reputation: 2391
Basically the problem here and how you want to solve it is a little bit more complicated.
First of all the javascript code is not valid and executing this script will return None
.
Much simpler version of the script is driver.execute_script("return confirm('...')")
but the problem here will be that the alert will pop up and the python code will continue so it will still return None
.
What you can do is to execute confirm('Yes or No?')
store it in variable, wait until alert is gone and return this variable.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoAlertPresentException
# small helper class to wait untill alert is no longer present
class alert_is_not_present(object):
""" Expect an alert to not to be present."""
def __call__(self, driver):
try:
alert = driver.switch_to.alert
alert.text
return False
except NoAlertPresentException:
return True
self.driver.execute_script("choice = confirm('yes or no')")
# Give some large timeout so you're sure that someone will have time to click
# Wait until user makes a choice
WebDriverWait(self.driver, 10000).until(alert_is_not_present())
# retrieve the choice
choice = self.driver.execute_script('return choice')
if choice:
print('Success!')
else:
print('Failed')
Upvotes: 1