【问题标题】:Python Xpath: lxml.etree.XPathEvalError: Invalid predicatePython Xpath:lxml.etree.XPathEvalError:无效谓词
【发布时间】:2016-07-26 18:03:10
【问题描述】:

我正在尝试学习如何抓取网页,在教程中我使用下面的代码抛出了这个错误:

lxml.etree.XPathEvalError: Invalid predicate

我正在查询的网站是(不要评判我,这是培训视频中使用的那个:/):https://itunes.apple.com/us/app/candy-crush-saga/id553834731

导致错误的xpath字符串在这里:

links = tree.xpath('//div[@class="center-stack"//*/a[@class="name"]/@href')

我正在使用 LXML 和请求库。

如果您需要任何其他信息,我很乐意提供!

【问题讨论】:

  • 使用了什么样的教程......只是想知道
  • 1) 请隔离错误行为并提供代码 2) 你想在教程中实现什么
  • 你不要关闭方括号
  • @splash58 - 谢谢!这是我的错误,我错过了中心堆栈 div 上的关闭“]”。我应该发现的!感谢您的帮助。现在工作正常。

标签: python xpath web-scraping python-requests lxml.html


【解决方案1】:
print(tree.xpath('//div[@class="center-stack"]//*/a[@class="name"]/@href'))

您在"center-stack" 之后缺少结束]

您也可以只从div[@class="content"] 中提取a[@class="name"] 标签

 tree.xpath('//div[@class="content"]//a[@class="name"]/@href')

两者都会给你你想要的href:

In [19]: import  requests

In [20]: from lxml.html import fromstring


In [21]: r = requests.get("https://itunes.apple.com/us/app/candy-crush-saga/id553834731")

In [22]: tree = fromstring(r.content)

In [23]: a = tree.xpath('//div[@class="content"]//a[@class="name"]/@href')

In [24]: b =  tree.xpath('//div[@class="center-stack"]//*/a[@class="name"]/@href')

In [25]: print(a == b)
True

In [26]: print(a)
['https://itunes.apple.com/us/app/word-search-puzzles/id609067187?mt=8', 'https://itunes.apple.com/us/app/cookie-jam/id727296976?mt=8', 'https://itunes.apple.com/us/app/jewel-mania/id561326449?mt=8', 'https://itunes.apple.com/us/app/jelly-splash/id645949180?mt=8', 'https://itunes.apple.com/us/app/bubble-island/id531354582?mt=8']

In [27]: print(b)
['https://itunes.apple.com/us/app/word-search-puzzles/id609067187?mt=8', 'https://itunes.apple.com/us/app/cookie-jam/id727296976?mt=8', 'https://itunes.apple.com/us/app/jewel-mania/id561326449?mt=8', 'https://itunes.apple.com/us/app/jelly-splash/id645949180?mt=8', 'https://itunes.apple.com/us/app/bubble-island/id531354582?mt=8']

【讨论】:

  • 感谢您的帮助帕德莱克。你和@Splash58 注意到我错过了中心堆栈 div 的结束“]”标记。
  • @MichaelMartinez,别担心,你只想要这五个链接,是吗?
  • 稍后在教程中,他们会告诉您如何爬取这些链接并从这些页面获取相同的信息,但我还没有看到那个视频。所以这就是我最需要的。非常感谢你的帮助。这样一个蹩脚的错误不容错过!
  • @MichaelMartinez,没问题,我自己已经做过很多次了。
猜你喜欢
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2017-10-12
  • 2018-12-25
相关资源
最近更新 更多