How to Get Int from JS Prompt Using Selenium in Python

Tags: , , ,



I am trying to create a prompt for a number from the user on a web page while using selenium in python.

This is the code I have written but it returns None

driver = webdriver.Chrome()
driver.get('https://www.google.com')

input_number = driver.execute_script('return parseInt(prompt("Enter a number", 20));')

print(input_number)

Answer

So I figured out the answer to my question.

Here is the code for anyone who might have the same issue:

from selenium.common.exceptions import UnexpectedAlertPresentException

driver = webdriver.Chrome()
driver.get('https://www.google.com')

while True:
    try:
        driver.execute_script("var a = prompt('Enter a number');document.body.setAttribute('user-manual-input', a)")
        sleep(10)  # must 
        print(driver.find_element_by_tag_name('body').get_attribute('user-manual-input')) # get the text
        break

     except (UnexpectedAlertPresentException):
        pass


Source: stackoverflow