Hello I am using selenium webdriver to get the position of the cursor in X,Y coordinates in a determined moment on the webdriver screen. I am trying a method that I found by implementing it by using diver.execute_script(), but I am having some issues with the implementation,
I am injecting the script described in the following site: https://www.dev-notes.com/blog/2008/07/30/get-current-mouse-cursor-position-with-javascript/
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
get_cursor_coordinates = """
window.onload = init;
function init() {
if (window.Event) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorXY;
}
function getCursorXY(e) {
document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
"""
self.driver.execute_script(get_cursor_coordinates)
script_vars = self.driver.execute_script('getCursorXY(null)')
When I execute the script in selenium to get the cursor coordinates, I get the following error:
selenium.common.exceptions.JavascriptException: Message: javascript error: getCursorXY is not defined
(Session info: chrome=94.0.4606.61)
I would like to know how to properly execute the script with Selenium in Python in order to get the X,Y coordinates of the cursor position
You can find mouse position with pyautogui library. Install pyautogui, and then
import pyautogui
mousePosition = pyautogui.displayMousePosition()