Carl
Carl

Reputation: 73

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?

Upvotes: 1

Views: 6218

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

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
    

Upvotes: 2

Barry the Platipus
Barry the Platipus

Reputation: 10460

The OP doesn't confirm the url where this button lives, so I can test the solution:

button = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "sc-pjTqr")))

There are other ways as well.

Upvotes: 0

Related Questions