Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to override the .click() method of selenium.webdriver.remote.webelement.WebElement. Also I want that overrided click() method to be called implicitly whenever I perform click operation e.g,

elem = driver.find_element_by_xpath('//some_xpath')
elem.click()

Is there anyway to achieve this ?

Any help will be much appreciated, Thanks.

share|improve this question
1  
You might want to take a look at the splinter framework, it puts a abstraction layer to selenium and basically already does what you want splinter.readthedocs.org/en/latest – sousatg Apr 27 '16 at 7:58
    
Thanks. But I need this solution for selenium driver. – Hassan Mehmood Apr 27 '16 at 9:07
    
You can check the splinter source code to check how they are doing it and replicate it. – sousatg Apr 27 '16 at 12:19
up vote 3 down vote accepted

To override the click method :

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


# monkey patch the click method :

def WebElement_click(self):
    """Clicks the element."""
    print("my click")
    self._execute(Command.CLICK_ELEMENT)

WebElement.click = WebElement_click


# usage example :

driver = webdriver.Chrome()
driver.get('https://stackoverflow.com')
driver.find_element_by_id("nav-questions").click()
share|improve this answer
    
Worked like a charm, Thank You :) – Hassan Mehmood Apr 28 '16 at 4:31

I think actually overriding the click() method might prove tricky and result in unwanted behavior. You might be able to achieve what you're after though using the EventFiringWebDriver. See the following example,

from selenium import webdriver
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener

# My custom event listener
class MyListener(AbstractEventListener):

    def before_click(self, element, driver):
        print "Event : before element click()"

    def after_click(self, element, driver):
        print "Event : after element click()"


# Get an event-firing-web-driver instance
driver = EventFiringWebDriver(webdriver.Firefox(), MyListener())

# Visit a site
driver.get("http://www.google.co.in/")

# Find an element
elem = driver.find_element_by_name("q")

# Click on element
elem.click()

# Close browser
driver.close()

Script above outputs,

Event : before element click()
Event : after element click()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.