检查Xpath是否存在

时间:2018-03-13 23:50:48

标签: python html selenium xpath beautifulsoup

我目前正在使用selenium,bs4和python进行抓取,但是我遇到了关于检查Xpath是否存在的问题,这是我的代码:

library(leaps)
data(iris)
a <- summary(regsubsets(Petal.Width~.,data=iris,nbest=5))
summary(a)
a$which
a$rsq
a$adjr2

正如您所看到的,它有一个简单的函数def hasXpath(xpath): try: browser.get(quote_page) self.browser.find_element_by_xpath(xpath) return True except: return False # IF PRICELIST EXISTS CONDITION/ if hasXpath("(//div[@id='product-header h4']//span)[last()-2]") or hasXpath("(//div[@id='product-header']//span)[last()-1]") or hasXpath("(//div[@id='product-header']//span)[last()]"): #No. of Items Per Retail(NEED LOGIN) somthing = browser.find_element_by_xpath("(//div[@id='product-header']//td)[21]").get_attribute("innerText") print(somthing) #Retail Price(NEED LOGIN) browser.get(quote_page) somthing1 = browser.find_element_by_xpath("(//div[@id='product-header']//span)[last()]").get_attribute("innerText") print(somthing1) if hasXpath("(//div[@id='product-header']//span)[last()-1]"): #1No. of Items Per Retail(NEED LOGIN) something = browser.find_element_by_xpath("(//div[@id='product-header']//td)[19]").get_attribute("innerText") print(something) #1Retail Price(NEED LOGIN) browser.get(quote_page) something = browser.find_element_by_xpath("(//div[@id='product-header']//span)[last()-1]").get_attribute("innerText") print(something1) else: print("It didn't go inside") ,我在其下面的IF语句中传递条件的xpath。但是,当我测试它时,一切似乎都要转向else语句。我也试过加倍真实情况但没有运气。在实施这个时我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题

您似乎正在使用不存在的变量:self。 (至少,您的代码片段没有任何内容表明它可能存在或者这些可能是实例方法。)

如果您移除包裹try: ... except: ...,我打赌您会看到以下错误:

NameError: name 'self' is not defined

解决方案

假设已定义browser,只需删除self.

奖金1:更好的异常处理

一般来说,你应该:

  • 尽可能缩小您预期失败的内容(try:块中包含的内容)和
  • 在您处理的例外中尽可能具体。

在您的情况下,看起来您只想保护find_element_by_xpath()并且只想捕获Selenium的NoSuchElementException

browser.get(quote_page)
try:
    browser.find_element_by_xpath(xpath)
    return True
except NoSuchElementException:
    return False

这种特异性允许使用NameError导致self冒泡到您可能看到的位置,从而省去了在此处发布问题的麻烦。

奖励2:更高效的页面加载

你正在调用browser.get(quote_page)多达六次:在你的剧本体内两次;并且一次进入hasXpath函数,这被称为四次。

由于您始终在加载同一页面,因此只需在脚本开头处执行一次。