Get JavaScript window value using Selenium WebDriver

Imagine there is a button that opens a JavaScript tooltip to show data to users and allows them to easily copy.

<!DOCTYPE html>
<html>

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

</html>
Run codeHide result

When automating a button using Selenium WebDriver, how to get the value of such a help window (i.e., the coordinates in this case need these values ​​for future use)? The WebDriver API provides a method for retrieving the text of such a tooltip (in this example, this This is your coordinates), but not the value, as far as I can see.

You can also consider the original JavaScript solution (without resorting to the attribute of the onclickelement <button>, of course, I put an event handler in the DOM to just illustrate the problem).

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"?
+4
1

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()
+1

Source: https://habr.com/ru/post/1667089/


All Articles