1

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?

P A N
  • 5,642
  • 15
  • 52
  • 103
  • 1
    So is this at core a Python question, how to write exception-handling code? You're looking for a NoSuchElementException (says http://selenium-python.readthedocs.org/en/latest/locating-elements.html). Try the code example at http://stackoverflow.com/a/12150013/423105 – LarsH Jun 04 '15 at 15:13

2 Answers2

1

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
peetya
  • 3,578
  • 2
  • 16
  • 30
0

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"
P A N
  • 5,642
  • 15
  • 52
  • 103