gpt4 book ai didi

javascript - 使用 Selenium WebDriver 获取 JavaScript 提示框的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:26:35 24 4
gpt4 key购买 nike

想象一下,有一个按钮可以打开一个 JavaScript 提示框,向用户显示数据并允许他们轻松复制。

<!DOCTYPE html>
<html>

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

</html>

当使用 Selenium WebDriver 自动化按钮时,如何获取此类提示框的值(即本例中的坐标,需要这些值以供进一步使用)? WebDriver API 提供了一种方法来获取此类提示框的文本(在本例中为 This is your coordinates ),但据我所知不是该值。

native JavaScript 解决方案也可以考虑(当然不访问 onclick 元素的 <button> 属性。我将事件处理程序放在 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"?

最佳答案

仅适用于 Windows

如您所见,当提示打开时,输入字段中的所需值已被选中(突出显示)。您可以复制它们,然后使用剪贴板中的这些值。我尝试了常见的 selenium 方法来发送 CTRL+C 组合,但它不能作为 find_element().send_keys()switch_to_alert .send_keys() 似乎工作方式不同......

所以我用了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()

关于javascript - 使用 Selenium WebDriver 获取 JavaScript 提示框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41710631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com