【问题标题】:Try alternative xpaths, or else continue尝试替代 xpath,否则继续
【发布时间】:2015-08-19 06:14:18
【问题描述】:
我用 Selenium 拼凑了一个网络爬虫,它使用 XPath 来查找元素。在我正在抓取的网页上,有两种可能的布局被加载,具体取决于内容。
如果我在错误的布局上运行我的代码,我会收到错误:Message: Unable to locate element: {"method":"xpath","selector":
如果第一个 xpath 不存在,我如何创建一个尝试替代 xpath 的 try/except(或类似)?或者如果不存在,继续下一段代码?
【问题讨论】:
标签:
python
selenium
xpath
try-except
【解决方案1】:
我没有使用 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
【解决方案2】:
这是一个简单的解决方案:
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"