click() method in Selenium Python

click() method in Selenium Python is used to click on the specified element, and this post will discuss it in detail using Selenium and Python.

  • Method declaration – def click(self) -> None
  • What does it do? – This function will perform a click operation on the specified WebElement.

Note: click() method performs a left click.

Code Example

Let’s try to click on the highlighted element below. This element is present on our playground website – https://testkru.com/Elements/Buttons.

Left click button

We can see that the element id’s is “leftClick“, and use it to find the element using find_element() method.

element = driver.find_element(By.ID, 'leftClick')

then, we can use the click() method to click the button.

element.click()

Whole Code

from selenium import webdriver
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options)
driver.get("https://testkru.com/Elements/Buttons")

element = driver.find_element(By.ID, 'leftClick')
element.click()

Above code will click on the button, which is also indicated by the change in the button’s text after clicking.

left clicked button
What if we try to click on an invisible or hidden element?

click() method can only be used to click on elements that are visible on the webpage, but what will happen if we try to click on an invisible element?

In the below image, we are pointing at an invisible element whose id is “invisibleField“. This element is present on the https://testkru.com/Elements/TextFields page.

Invisible field
from selenium import webdriver
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options)
driver.get("https://testkru.com/Elements/TextFields")

element = driver.find_element(By.ID, 'invisibleField')
element.click()

Output –

    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

We received an ElementNotInteractableException. Therefore, always ensure the element you intend to click is visible on the webpage.

We hope that you like the article. If you have any doubts or concerns, please write us in the comments or mail us at admin@codekru.com.

Related Article
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *