[英]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. 想象一下,有一个按钮可以打开一个JavaScript提示框,向用户显示数据并允许他们轻松复制。
<!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)? 使用Selenium WebDriver自动化按钮时,如何获取此类提示框的值(即本例中的坐标,需要这些值以供进一步使用)? 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. WebDriver API提供了一种方法来获取这样的提示框的文本(在这个例子中,它This is your coordinates
),但不是我能看到的值。
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). 原生JavaScript解决方案也可以考虑(当然不能访问<button>
元素的onclick
属性。我将事件处理程序放在DOM中只是为了简单地说明问题)。
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 仅适用于Windows
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... 我尝试了常见的selenium
方法来发送CTRL+C
组合,但它不能用作find_element().send_keys()
和switch_to_alert.send_keys()
似乎工作方式不同......
So I used Python AutoHotKey + win32clipboard
: 所以我使用了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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.