python中判断xpath是否存在_检查Xpath是否存在

博主在使用Python的Selenium和BeautifulSoup库进行网页抓取时遇到问题,主要涉及Xpath的检查和元素定位。代码中定义了一个`hasXpath()`函数用于检查Xpath是否存在,然后根据不同的Xpath条件执行相应的元素获取操作。然而,测试过程中,代码总是进入else语句,即Xpath检查似乎始终失败。博主尝试了多种路径,但未能解决问题。
摘要由CSDN通过智能技术生成

我目前正在使用selenium、bs4和python进行抓取,但是在检查Xpath是否存在时遇到了一个问题,下面是我的代码: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")

如您所见,它有一个简单的函数hasXpath(),我在它下面的IF语句中为条件传递xpath。然而,当我测试它时,一切似乎都指向else语句。我也试着把真实的情况加倍,但没有运气。我在实施这一点时做错了什么?在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值