2

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.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217

1 Answers1

0

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
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
  • It seems like using XPATH with text() is the only one that's working for me. I'll use it since its a solution for clicking the button. – John Frames Jul 26 '20 at 15:24
  • Also, how did you get the XPATH? When I try to get it, I have `/html/body/div[5]/div/div[2]/div[5]/div[1]/div[3]/div[1]/span` and not `//*[text()='login or register']` – John Frames Jul 26 '20 at 15:38
  • @JohnFrames These are generic techniques to convert _linkText_ / _partialLinkText_ into _xpath_. – DebanjanB Jul 26 '20 at 16:42
  • @JohnFrames Glad to be able to help you. [Vote up questions and answers](https://stackoverflow.com/help/privileges/vote-up) that you found helpful for the benifit of the future readers. See [Why is voting important](https://stackoverflow.com/help/why-vote). – DebanjanB Jul 26 '20 at 20:33