Trying to click a button but keep getting an error with xpath

Viewed 70

I am trying to automate pulling credit charges into an excel sheet; I have managed to get the login working. Once I enter the website, there's a button titled "Search". I cant seem to figure out how to have that button clicked.

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

import time

chromedriver = "C:/Python_Ex/chromedriver_win32/chromedriver.exe"
driver = webdriver.Chrome(chromedriver)
delay = 30
driver.get("https://global.americanexpress.com/activity/date-range?from=2020-05-01&to=2020-05-30")

driver.find_element_by_xpath('//*[@id="eliloUserID"]').send_keys("removed")
driver.find_element_by_xpath('//*[@id="eliloPassword"]').send_keys("removed")
driver.find_element_by_xpath('//*[@id="loginSubmit"]').click()

time.sleep(10)

#print(driver.find_elements_by_xpath('//*[@id="root"]/div[1]/div/div[2]/div/div/div[5]/div/div[3]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/section/div[4]/div[2]/button'))
search_button = driver.find_elements_by_xpath('//*[@id="root"]/div[1]/div/div[2]/div/div/div[5]/div/div[3]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/section/div[4]/div[2]/button')
search_button.click()

html tag is as follows

<button class="btn btn-fluid" tabindex="0" type="button"> <span>Search</span></button>

Xpath as follows

//*[@id="root"]/div[1]/div/div[2]/div/div/div[5]/div/div[3]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/section/div[4]/div[2]/button

Any help is appreciated.

2 Answers

After login submited, try to add the below code:

...
...
driver.find_element_by_xpath('//*[@id="loginSubmit"]').click()

wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-fluid']//span[text()='Search']"))).click()

Following import:

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

To click() on the <button> with text as Search using Selenium you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-fluid[type='button']>span"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-fluid']/span[text()='Search']"))).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
    
Related