Jeevan
Jeevan

Reputation: 477

Selenium returning NoSuchElementException but the element exists

I am having this code

driver.implicitly_wait(300) # I have tried different timers
driver.find_element_by_xpath("(//button[@aria-pressed='false'])[1]").click()

But I get this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//button[@aria-pressed='false'])[1]"}

However, this exists in my HTML content, like:

<div class="webix_el_box" style="width:90px; height:26px">
    <button aria-pressed="false" type="button" class="webix_img_btn" style="line-height:22px;">
        <span class="webix_icon_btn fa-lock red" style="max-width:22px;">
        </span> Read Only
    </button>
</div>

I have also tried to use the XPath expression:

//button[@class='webix_img_btn']//child::span[@class='webix_icon_btn fa-lock red']

Both XPath expressions worked fine in Google Chrome. In the website I am able to find the button using Ctrl + F and 'Read Only', can I use it in Selenium?


It is not working because of Selenium Driver is one page behind ajax call after large json data download.

Upvotes: 1

Views: 1749

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

To click on the element with text as Read Only you have 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.webix_el_box > button.webix_img_btn"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='webix_el_box']/button[@class='webix_img_btn' and contains(., 'Read Only')]"))).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
    

References

You can find a couple of relevant discussions on NoSuchElementException in:

Upvotes: 1

aidan0626
aidan0626

Reputation: 307

Try doing just

driver.implicitly_wait(300)
driver.find_element_by_xpath("//button[@aria-pressed='false']").click()

This will click on the first element that satisfies the requirements.

Upvotes: 0

Related Questions