Search code examples
pythonseleniumselenium-webdriverxpathfindelement

If condition is not working when browser.find_element_by_xpath has no data or unable to locate element


            if not(browser.find_element_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a')):
                email = 'No data'
            else:
                email = browser.find_element_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a').get_attribute("textContent")
            print(email)
  1. browser.find_element_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a')).get_attribute("textContent") don't have data.

  2. i wrote a condition if we dont have data in the provided xpath it should replace with 'no data'.

  3. if data present we need to store email address else we need to store default value (i.e) 'no data'

  4. this is the error i am receiving every time.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a"} (Session info: chrome=88.0.4324.150)


Solution

  • You could run this in a try/except clause.

    try:
        email = browser.find_element_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a').get_attribute("textContent")
    except:
        email = 'No data'
    

    You could also use find_elements, which will return an empty list if the element is not found. You can then test whether the list is empty using an if statement.

    if browser.find_elements_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]'):
        email = browser.find_element_by_xpath('//div[@id="MainCopy_ctl13_presentJob_EmailAddressPanel"]//a').get_attribute("textContent")
    else:
        email = 'No data'