P A N
P A N

Reputation: 5922

Try alternative xpaths, or else continue

I have pieced together a web crawler with Selenium that uses XPath to find elements. On the web page I'm scraping, there are two possible layouts that are loaded, depending on the content.

If I run my code on the wrong layout, I get the error: Message: Unable to locate element: {"method":"xpath","selector":

How can I create a try/except (or similar) that tries an alternative xpath, if the first xpath is not present? Or if none is present, continue on to the next section of code?

Upvotes: 1

Views: 754

Answers (2)

P A N
P A N

Reputation: 5922

Here is the simple solution:

try:
    element_in_layout_1 = driver.find_element_by_xpath("my_xpath_1")
except:
    try:
        element_in_layout_2 = driver.find_element_by_xpath("my_xpath_2")
    except:
        print "No Element was found"
        pass
    else:
        print "Element in Layout 2 was found"
else:
    print "Element in Layout 1 was found"

Upvotes: 0

peetya
peetya

Reputation: 3618

I haven't got experience with Python so I'm not able to write you an example code, but you should create two try/catch (or in this case try/except) block where you try to find your element with find_element_by_xpath. After that catch the NoSuchElementException and you can work with the WebElement(s).

In JAVA it looks something like this:

  Boolean isFirstElementExist, isSecondElementExist = true;
  WebElement firstElement, secondElement;

  try {
    firstElement = driver.findElement(By.xpath("first xpath"));
  } catch (NoSuchElementException e) {
    isFirstElementExist = false;
  }

  try {
    secondElement = driver.findElement(By.xpath("second xpath"));
  } catch (NoSuchElementException e) {
    isSecondElementExist = false;
  }

  //... work with the WebElement

Upvotes: 1

Related Questions