How to right click and hold it in selenium python

Viewed 603

I'm looking to automate my web browser to rotate a map created using mapbox, however this can only be done by holding the right mouse down and panning around.

I know there is a click and hold option for the left click, but is there anything similar for right click? At present I can only do a single right click using context click

1 Answers

Unfortunately, this is not supported, but you can modify the source code of selenium in your site-packages directory, it's pretty straightforward since all you have to do is change the parameter for the pointer event in the click_and_hold method, to the same parameter as the pointer event in the context_click method, and then create a custom function for that.

Here's what I managed to do:

File 1: Locate and edit this file in
Lib/site-packages/selenium/webdriver/common/actions/pointer_actions.py

Add this function to the "PointerActions" class:

class PointerActions(Interaction):
    def move_to_location(self, x, y):
        ...
    def click(self, element=None):
        ...
    def context_click(self, element=None):
        ...

    # --- Add this function
    def context_click_and_hold(self, element=None):
        if element:
            self.move_to(element)
        self.pointer_down(MouseButton.RIGHT)
        return self
    # ---
    
    def click_and_hold(self, element=None):
        ...
    def release(self):
        ...
    def double_click(self, element=None):
        ...

File 2: Locate and edit this file in
Lib/site-packages/selenium/webdriver/common/action_chains.py

Add this function to the "ActionChains" class:

class ActionChains(object):
    def __init__(self, driver, duration=250):
        ...
    def click(self, on_element=None):
        ...

    # --- Add this function
    def context_click_and_hold(self, on_element=None):
        if on_element:
            self.move_to_element(on_element)

        self.w3c_actions.pointer_action.context_click_and_hold()
        self.w3c_actions.key_action.pause()

        return self
    # ---
    
    def click_and_hold(self, on_element=None):
        ...
    def context_click(self, on_element=None):
        ...
Related