Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move the mouse in Selenium?

I'm trying to simulate mouse movement across a random curve line or parabola so it looks like the mouse actually moved across the page. With Selenium, I only know how to click on an element but that doesn't simulate a real user on some websites. I want the mouse to move along a random line that I calculate, then click the element.

like image 574
User Avatar asked Aug 23 '15 14:08

User


2 Answers

The Python code would look like this (assuming your browser is Firefox):

driver = webdriver.Firefox(executable_path=driver_path)
action = webdriver.ActionChains(driver)
element = driver.find_element_by_id('your-id') # or your another selector here
action.move_to_element(element)
action.perform()

Please note that this doesn't move your physical cursor, but only invisible cursor of Selenium. To see if it worked, element must have some 'hover' effect. Also if you have already moved your cursor to an element and want to re-position it relatively, you can use:

action.move_by_offset(10, 20)    # 10px to the right, 20px to bottom
action.perform()

or even shorter:

action.move_by_offset(10, 20).perform()

More documentation is here: https://selenium-python.readthedocs.io/api.html

like image 69
Eugene Chabanov Avatar answered Sep 16 '22 18:09

Eugene Chabanov


The docs say you can use move_by_offset(xoffset, yoffset) function.

like image 30
Sait Avatar answered Sep 16 '22 18:09

Sait