Sam Krygsheld
Sam Krygsheld

Reputation: 2060

Adding functions to Selenium WebDriver WebElements using Python

While using Selenium WebDriver to test a website, I would like to have the ability to double click on a WebElement object without having to having to use class inheritance or mess with ActionChains. Ideally, it should be accessible in the webelement.double_click() form, just as click() is. This can be done by editing the WebElement.py file and simply adding the following to the WebElement class:

def double_click(self):
    self._execute(Command.DOUBLE_CLICK)

Simple enough. However, I update this library all the time, and this is liable to get overwritten. With that in mind, I'm trying to figure out a simple way to add this capability to the WebElement object from the file I'm working with. I have tried importing WebElement and defining the function like so:

from selenium import webdriver
from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webelement import WebElement

def double_click(self):
    self.execute(Command.DOUBLE_CLICK)

WebElement.double_click = double_click

Then when I run the browser (webdriver.Firefox()), double_click is defined for each element, but it does not function correctly. Instead, it raises

WebDriverException: Message: [JavaScript Error: "Argument to isShown must be of type Element" ...

The same error occurs when I redefine the click() function in the same way. I confirmed that the elements I am attempting to click are class 'selenium.webdriver.remote.webelement.WebElement', but it seems the wires are getting crossed somewhere, and I'm not sure how.

To be clear, I know that there are workarounds for this. The problem is not that I cannot double click - I just want to know if this is possible in a way similar to what I am attempting.

Upvotes: 2

Views: 1696

Answers (1)

Florent B.
Florent B.

Reputation: 42528

To monkey patch the double click method on the WebElement class:

def WebElement_double_click(self):
    self._parent.execute(Command.MOVE_TO, {'element': self._id})
    self._parent.execute(Command.DOUBLE_CLICK)
    return self

WebElement.double_click = WebElement_double_click

Upvotes: 1

Related Questions