Skip to content Skip to sidebar Skip to footer

Try Except In Python/selenium Still Throwing NoSuchElementException Error

I am trying to capture some website elements using selenium in python, and I am using try/except in case there is a specific element that cannot be found in that particular page. T

Solution 1:

I don't do python but if it were me, I would remove all the try/catches and replace them with find_elements_* and check for empty list. For example

replace

specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text

with

elements = result.find_elements_by_xpath(".//*[@class='specific']/div")
if elements
    specific_element = elements[0]

This basically just makes sure that any element is found before accessing it and you can avoid all the try/catches. I'm of the opinion that exceptions should be exceptional... rare. They shouldn't be expected or used as flow control, etc.


Solution 2:

You have to take care of a couple of points here :

  • There is no absolute necessity to try driver.get(url)
  • The issue is in the following block :

    try:
        specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text
    

Analysis

You have tried a chain of events before the try() actually comes into action :

  • Evaluate

    result.find_element_by_xpath(""".//*[@class="specific"]/div""")
    
  • Next

    result.find_element_by_xpath(""".//*[@class="specific"]/div""").text
    
  • Next

    specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text
    

So,

  • Once result.find_element_by_xpath(""".//*[@class="specific"]/div""") fails though NoSuchElementException is raised, try still remains silent.

Solution

A simple solution would be :

try:
    specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""")
    specific_element_text = specific_element.text
    # other works

except NoSuchElementException:
    specific_element = ""
    # other works

Post a Comment for "Try Except In Python/selenium Still Throwing NoSuchElementException Error"