Jack
Jack

Reputation: 461

Click a button on a website using selenium

I am trying to click a button on a website using selenium. Here's the html:

<form action="/login/" id="login" method="post" class="form-full-width">
   <input data-testid="loginFormSubmit" type="submit" class="btn btn-success btn-large" value="Log in" 
   tabindex="3">
</form>

Here's some of my code:

if __name__ == "__main__":
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, 100)
    driver.get ('https://www.url.com/login/')
    driver.find_element_by_name('username').send_keys('username')
    driver.find_element_by_name('password').send_keys('password')
    driver.find_elements_by_xpath("//input[@value='Log in' and @type='submit']")

I have also tried:

driver.find_element_by_value('log in').click()
driver.find_element_by_xpath("//a[@href='https://www.url.com/home/']").click()

However when I run it, it always comes up with this error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='https://www.url.com/home/']"}

I am new to selenium and web drivers, so any help would be appreciated.

Upvotes: 1

Views: 210

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193058

To click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-testid='loginFormSubmit'][value='Log in']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@data-testid='loginFormSubmit' and @value='Log in']"))).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
    

References

You can find a couple of relevant discussions on NoSuchElementException in:

Upvotes: 1

Related Questions