简体   繁体   中英

Get the value of a JavaScript prompt box with Selenium WebDriver

Imagine there is a button that opens up a JavaScript prompt box to show data to users and allow them to copy easily.

 <!DOCTYPE html> <html> <body> <button id="show-coordinates" onclick="prompt('This is your coordinates', '4.684032, -74.109663');"> Show Coordinates </button> </body> </html> 

When automating the button using Selenium WebDriver, how to get the value of such prompt box (ie the coordinates in this case, need those values for further use)? WebDriver API provides a method to get the text of such prompt box (in this example, it's This is your coordinates ), but not the value as far as I can see.

Native JavaScript solution can be considered too (not accessing the onclick attribute of <button> element of course. I put the event handler in DOM just to illustrate the problem easily).

driver.find_element(:id, 'show-coordinates').click
popup = driver.switch_to.alert
puts popup.text # This is your coordinates
# But how to get "4.684032, -74.109663"?

For Windows only

As you can see when prompt is opened required values in input field are selected (highlighted). You can copy them and then use those values from clipboard. I tried common selenium methods to send CTRL+C combination, but it's not working as find_element().send_keys() and switch_to_alert.send_keys() seem to work differently...

So I used Python AutoHotKey + win32clipboard :

import win32clipboard
import time
import ahk
from selenium import webdriver

# Steps to open Prompt
driver = webdriver.Chrome()
driver.get(URL)
driver.find_element_by_tag_name("button").click()
driver.switch_to_alert()

# Copy prompt content
ahk.start()
ahk.ready()
ahk.execute("Send,^C") # sending CTRL + C
time.sleep(2) # Required... for some reason

driver.switch_to.alert.accept()

# Get values from clipboard
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

print(data) # Output is "4.684032, -74.109663"

driver.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM