0

I'm testing a web UI using Selenium in Python. I've come to a test case where a button should be redirected to another page after clicking.

However, every time the code executes without any exceptions but still the page is not being redirected. I'm sure that the button gets clicked correctly, as the button animation and mouse cursor changes.

I tried with direct click method and also Javascript click method

`sign_in = driver.find_element(By.CSS_SELECTOR, "button[class='btn btn-primary-blue']")
 sign_in.click()
 driver.execute_script("arguments[0].click();", sign_in)`

and the element

`<div class="editorial-hero-banner--footer pb-35 pb-sm-0"><div class="SSOLogin__Container"><button type="button" class="btn btn-primary-blue">Sign in / Register</button></div></div>
    <div class="SSOLogin__Container"><button type="button" class="btn btn-primary-blue">Sign in / Register</button></div>
        <button type="button" class="btn btn-primary-blue">Sign in / Register</button>`
  • There could be a lot of reasons for this. We need more information! I copied your code and it worked for me. But since I didn't have the full page I had to add `onclick="alert(1)"` to check if clicking the button works. – muhmann Jul 04 '23 at 06:40

1 Answers1

0

Given the HTML:

<div class="editorial-hero-banner--footer pb-35 pb-sm-0">
    <div class="SSOLogin__Container">
        <button type="button" class="btn btn-primary-blue">Sign in / Register</button>
    </div>
</div>

The Sign in / Register element is a dynamic element.


Solution

To click on the clickable element 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, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.SSOLogin__Container > button.btn.btn-primary-blue"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary-blue'][starts-with(., 'Sign in') and contains(., 'Register')]"))).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
    

Alternative

As an alternative you can use the executeScript() method from JavascriptExecutor as follows:

  • Using CSS_SELECTOR:

    driver.execute_script("arguments[0].click();", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.SSOLogin__Container > button.btn.btn-primary-blue"))))
    
  • Using XPATH:

    driver.execute_script("arguments[0].click();", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary-blue'][starts-with(., 'Sign in') and contains(., 'Register')]"))))
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352