Search code examples
pythonseleniumxpathwebdriverwaitlinktext

How to click on a button by the link text using Selenium and Python


I know, there are plenty of tutorials out there for this task. But it seems like I'm doing something wrong, I need help by telling me how to press it, doesn't need to be by text.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, 'login or register'))
    )
    element.click()
except:
    print('exception occured')
    driver.quit()

I'm trying to press the "login or register" button from the site wilds.io, but it seems like it can't find that button after 10 seconds. I'm probably accessing the button in a wrong way.


Solution

  • To click on the element with text as login or register you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

    • Using LINK_TEXT:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "login or register"))).click()
      
    • Using PARTIAL_LINK_TEXT:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "login or register"))).click()
      
    • Using XPATH using text():

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[text()='login or register']"))).click()
      
    • Using XPATH using contains():

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(., 'login or register')]"))).click()
      
    • Note: You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC