Home > OS >  Python Selenium - Find Element not working for a button
Python Selenium - Find Element not working for a button

Time:12-13

Can anyone assist in clicking a button on a website using Selenium? On the main landing page, I want to click the "Confirm" button. I get an no such element: Unable to locate element: error. Please see my code below:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
  
driver = webdriver.Chrome(r"./driver/chromedriver")
  
driver.get("https://www.xe.com/currencytables/")
  
driver.maximize_window()
time.sleep(10)
  
login_button = driver.find_element(By.CLASS_NAME, "button__BaseButton-sc-1qpsalo-0 clGTKJ")
button.click()

CodePudding user response:

  1. button__BaseButton-sc-1qpsalo-0 clGTKJ are 2 class name values. To use multiple class name values you can use CSS_SELECTOR or XPATH but not CLASS_NAME because this method receives single class name value.
  2. button__BaseButton-sc-1qpsalo-0 clGTKJ class names appearing in 3 elements on that page. I guess you wanted to click a confirm button, if so another selector can be used, as following.
  3. You should not use hardcoded sleeps like time.sleep(10). WebDriverWait expected_conditions explicit waits should be used instead.

The following code works:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)

wait = WebDriverWait(driver, 5)
actions = ActionChains(driver)

url = "https://www.xe.com/currencytables/"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

The result is

enter image description here

  • Related