Home > other >  Selenium doesn't find element by CssSelector
Selenium doesn't find element by CssSelector

Time:04-28

HTML:

<button type="button"  style="width: auto;"><div tabindex="0" ><span  style="letter-spacing: 0.1em;">TRANSFER</span></div></button>

Code trials:

transfer_input = driver.find_element(by=By.CSS_SELECTOR,value= '//*[@id="root"]/div/div[2]/div/div[1]/div[3]/div/div[2]/div[1]/div/div/div[5]/button')
transfer_input.click()

Snapshot of the error:

https://img.codepudding.com/202204/cb58c2cbf779489d9b1ff5add9f8e415.png

I tried do by Xpath, or class name it still doesn't find.

CodePudding user response:

You are using a XPath, not a CSS Selector. Try these one of these three options.

transfer_input = wait.until(
    EC.presence_of_element_located(
        (By.XPATH, '//*[@id="root"]/div/div[2]/div/div[1]/div[3]/div/div[2]/div[1]/div/div/div[5]/button')
    )
)
transfer_input.click()

OR

transfer_input = wait.until(
    EC.element_to_be_clickable(
        (By.XPATH, '//*[@id="root"]/div/div[2]/div/div[1]/div[3]/div/div[2]/div[1]/div/div/div[5]/button')
    )
)
transfer_input.click()

OR

import time
time.sleep(10) # sleep for 10 seconds
transfer_input = driver.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div[1]/div[3]/div/div[2]/div[1]/div/div/div[5]/button')
transfer_input.click()

CodePudding user response:

There are two things as follows:

  • You have mentioned about using by=By.CSS_SELECTOR but the value was of xpath.

  • Instead of a absolute xpath you can construct a relative xpath.

  • Ideally to click on a 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, "button[type='button'] > div[class*='secondary-btn'] > span"))).click()
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button/div[contains(@class, 'secondary-btn')]/span[@class and text()='TRANSFER']"))).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