繁体   English   中英

尝试其他xpath,否则继续

[英]Try alternative xpaths, or else continue

我已经使用Selenium拼凑了一个Web爬网程序,该爬虫使用XPath查找元素。 在要抓取的网页上,根据内容,有两种可能的布局被加载。

如果我在错误的布局上运行代码,则会出现错误: Message: Unable to locate element: {"method":"xpath","selector":

如果不存在第一个xpath,我如何创建try / except (或类似方法)尝试另一个xpath? 或者,如果不存在,请继续执行下一部分代码?

我没有使用Python的经验,所以我无法为您编写示例代码,但是您应该创建两个try/catch (或者在这种情况下为try/except )块,在其中尝试使用find_element_by_xpath查找元素。 之后,捕获NoSuchElementException,您可以使用WebElement。

在JAVA中看起来像这样:

  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

这是简单的解决方案:

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM