提取Item
从网页中提取数据有很多方法。Scrapy使用了一种基于 XPath 和CSS 表达式机制:Scrapy Selectors
构造选择器
Scrapy selector是以 文字(text) 或 TextResponse
构造的Selector 实例。其根据输入的类型自动选择最优的分析方法(XML vs HTML):
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
1、以文字构造:
2、以response构造:
为了方便起见,response对象以 .selector 属性提供了一个selector:
使用选择器
使用 Scrapy shell (提供交互测试)和位于Scrapy文档服务器的一个样例页面,来解释如何使用选择器:
http://doc.scrapy.org/en/latest/_static/selectors-sample1.html
这里是它的HTML源码:
<html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
</head>
<body>
<div id='images'>
<a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
<a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
<a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
<a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
<a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
</div>
</body>
</html>
1、首先, 打开shell:
scrapy shell http://doc.scrapy.org/en/latest/_static/selectors-sample1.html接着,当shell载入后,将获得名为
response
的shell变量,其为响应的response,并且在其
response.selector
属性上绑定了一个selector。
2、为了提取真实的原文数据,你需要调用 .extract()
方法如下:
更多的xpath语法可以参考http://www.w3school.com.cn/xpath/xpath_syntax.asp