我用 Selenium 拼凑了一个网络爬虫,它使用 XPath 来查找元素。在我正在抓取的网页上,根据内容加载了两种可能的布局。
如果我在错误的布局上运行代码,则会收到错误:消息:无法定位元素:{“method”:“xpath”,“selector”:
如果第一个 xpath 不存在,如何创建尝试替代 xpath 的 try
/ except
(或类似)?或者,如果不存在,请继续执行下一部分代码?
最佳答案
我没有使用 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
关于python - 尝试替代 xpath,否则继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647147/