使用 xpath 抓取网页内容不起作用

Posted

技术标签:

【中文标题】使用 xpath 抓取网页内容不起作用【英文标题】:Scraping web content using xpath won't work 【发布时间】:2014-09-23 16:27:35 【问题描述】:

我正在使用 xpath 来抓取特定的亚马逊网页,但它不起作用。任何人都可以给我一些建议吗?这是该页面的链接: a link

我想抓取这些:“有趣的信用卡大小的照片” 我正在使用的代码在这里:

from lxml import html
import requests

url = 'http://www.amazon.co.uk/dp/B009CX5VN2'
page = requests.get(url)
tree = html.fromstring(page.text)
feature_bullets = tree.xpath('//*[@id="feature-bullets"]/ul/li[1]/span/text()')

但是 feature_bullets 总是空的。真的需要帮助。

【问题讨论】:

我提请您注意Amazon UK's Conditions of Use & Sale 的第 3 部分的第二段。 【参考方案1】:

我下载的 HTML 与您的期望不符。这是适合我的表达方式:

tree.xpath('//div[@id="technicalProductFeaturesATF"]/ul/li[1]/text()')

完整的程序:

from lxml import html
import requests
from pprint import pprint

url = 'http://www.amazon.co.uk/dp/B009CX5VN2'
page = requests.get(url)
tree = html.fromstring(page.text)
feature_bullets = tree.xpath('//div[@id="technicalProductFeaturesATF"]/ul/li/text()')

pprint(feature_bullets)

结果:

$ python foo.py 
['Fun, credit card-sized prints',
 'LCD film counter and shooting mode display',
 'Camera mounted mirror for self portraits',
 'Powered by CR2 Batteries, Built-in, Automatic electronic flash',
 'Fujifilm Instax Mini 25 + 30 Instax Mini Film']

【讨论】:

感谢您的回答。我注意到程序正在读取的 html 与 chrome 或任何其他浏览器中的 html 略有不同,尽管我不知道为什么会这样。也许每个浏览器都有自己的标准格式。 您可以考虑sending a user-agent string 连同您的请求。如果您使用user-agent from your browser,您可能会得到相同的页面。 哦!永远不知道。很高兴知道。现在挖掘...谢谢

以上是关于使用 xpath 抓取网页内容不起作用的主要内容,如果未能解决你的问题,请参考以下文章

xPath Helper

Chrome安装爬虫必备插件:Xpath Helper高效解析网页内容(实测有效)

网页解析库-Xpath语法

Rvest 和 Google 新闻网页抓取:不起作用

点击后无法抓取下一个网页

如何使用Java抓取网页上指定部分的内容