简体   繁体   English

Python Xpath:lxml.etree.XPathEvalError:谓词无效

[英]Python Xpath: lxml.etree.XPathEvalError: Invalid predicate

I'm trying to learn how to scrape web pages and in the tutorial I'm using the code below is throwing this error: 我正在尝试学习如何抓取网页,在教程中我使用下面的代码是抛出这个错误:

lxml.etree.XPathEvalError: Invalid predicate

The website I'm querying is (don't judge me, it was the one used in the training vid :/ ): https://itunes.apple.com/us/app/candy-crush-saga/id553834731 我要查询的网站是(不要评判我,这是培训视频中使用的那个:/): https//itunes.apple.com/us/app/candy-crush-saga/id553834731

The xpath string that causes the error is here: 导致错误的xpath字符串在这里:

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

I'm using the LXML and requests libraries. 我正在使用LXML并请求库。

If you need any additional info I'm happy to provide! 如果您需要任何其他信息,我很乐意提供!

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

You were missing a closing ] after "center-stack" . "center-stack"之后你错过了一个结束]

You can also just pull the a[@class="name"] tags from div[@class="content"] 您也可以从div[@class="content"]提取a[@class="name"]标签

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

Both will give you the hrefs you want: 两者都会给你你想要的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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM