Search code examples
pythonseleniumselenium-webdrivercss-selectorswebdriverwait

Selenium findElement(By.CSS_SELECTOR)


I have this button on the page:

<button type="submit" class="sc-pjTqr dzmlqP">Continue</button>`

I checked the documentation and StackOverflow answers and it seems to me that the solution should be:

continue = driver.find_element(By.CSS_SELECTOR,"button.sc-pjTqr.dzmlqP")

But does not work.

I searched for solutions, but I didn't understand. Why?


Solution

  • The classnames i.e. sc-pjTqr, dzmlqP are dynamically generated and is bound to chage sooner/later. They may change next time you access the application afresh or even while next application startup. So can't be used in locators.


    Solution

    To identify the element with text as Continue you can use the following locator strategy:

    • Using xpath:

      continue = driver.find_element(By.XPATH, "//button[text()='Continue']")
      

    Ideally to identify the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following locator strategy:

    • Using XPATH:

      continue = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Continue']")))
      
    • 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