Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can attach the mouse movement (pyautogui) to pyvirtualdisplay with selenium webdriver (python)?

I am trying to automatize a website how have a SWF inside.

I cant move the mouse with selenium, because is a SWF,so to fix this I use the pyautogui library.

Everything works fine!, but! when I use pyvirtualdisplay to hide the navigator the mouse is not attached, so I still see how pyautogui move my mouse.

My example code:

from selenium import webdriver
from pyvirtualdisplay import Display
import pyautogui

display = Display(visible=1, size=(1600,900))
display.start()


driver = webdriver.Firefox()
driver.set_window_size(1600,900)
driver.get('https://website.where.I.have.the.SWF.com')

sleep(5)
pyautogui.click(450, 180)

driver.close()
display.stop()

How I can attach the mouse to the pyvirtualdisplay instance?

like image 404
nguaman Avatar asked Mar 04 '16 14:03

nguaman


People also ask

How do you perform mouse actions in Selenium Python?

mouseMove / hover in python seleniumWith the object of the actions, you should first move to the menu element, and then move to the submenu item and click it or perform whatever action you wish.

Can a website detect PyAutoGUI?

No, as far as I know, there is no way for a website to detect the device or software (such as PyAutoGUI) which is making inputs, however, a site could detect robotic mouse movement etc., and you will not be able to pass CAPTCHAs.

How do you mouse hover and click in Selenium Python?

We can perform mouseover action in Selenium webdriver in Python by using the ActionChains class. We have to create an object of this class and then apply suitable methods on it. In order to move the mouse to an element, we shall use the move_to_element method and pass the element locator as a parameter.

How do you click and drag in Selenium Python?

In our case, we'll use these operations for drag and drop in Selenium Python by simulating click using click_and_hold, then dragging by using move_to_element or move_by_offset or combo, and by finally releasing, i.e., dropping the selected element.


1 Answers

You can monkey-patch pyautogui internals. Tested on 'xvfb' backend.

import os
from pyvirtualdisplay import Display
import pyautogui
import Xlib.display

v_display = Display(visible=1, size=(1600,900))
v_display.start()  # this changes the DISPLAY environment variable
# sadly, pyautogui does not detect this change
pyautogui._pyautogui_x11._display = Xlib.display.Display(
                os.environ['DISPLAY']
            )
...
pyautogui.click(...)  # clicks on v_display
...

v_display.stop()

Note: this should be sufficient to enable pyautogui mouse, using keyboard may require additional configuration of key mapping. For more info, please see: https://github.com/asweigart/pyautogui/blob/master/pyautogui/_pyautogui_x11.py

like image 186
Franek Avatar answered Sep 19 '22 07:09

Franek