Balamurugan PM
Balamurugan PM

Reputation: 21

Selenium webdriver python find element by xpath - Could not find element

I m trying to write a script with selenium webdriver python. When I try to do a

find_element_by_xpath("//*[@id='posted_1']/div[3]") 

it says

NoElementFoundException.

Can someone please help me here?

Regards Bala

Upvotes: 1

Views: 12024

Answers (2)

Saurabh Gaur
Saurabh Gaur

Reputation: 23835

If you are getting NoSuchElementException as your provided exception, There may be following reasons :-

  • May be you are locating with incorrect locator, So you need to share HTML for better locator solution.

  • May be when you are going to find element, it would not be present on the DOM, So you should implement WebDriverWait to wait until element visible as below :-

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    wait = WebDriverWait(driver, 10)
    
    element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))
    
  • May be this element is inside any frame or iframe. If it is, you need to switch that frame or iframe before finding the element as below :-

    driver.switch_to_frame("frame/iframe I'd or name")
    
    wait = WebDriverWait(driver, 10)
    
    element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))
    
    #Once all your stuff done with this frame need to switch back to default
    driver.switch_to_default_content();
    

Upvotes: 3

n1c9
n1c9

Reputation: 2697

that exception, unsurprisingly, means that that element wasn't available on the DOM. There are a couple of options here:

driver.implicitly_wait(10)

will tell the driver to wait 10 seconds (or any amount of time) after an element is not found/not clickable etc., and tries again after. Sometimes elements don't load right away, so an implicit wait fixes those types of problems.

The other option here is to do an explicit wait. This will wait until the element appears, and until the existence of that element is confirmed, the script will not move on to the next line:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 

element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))

In my experience, an implicit wait is usually fine, but imprecise.

Upvotes: 0

Related Questions