简介
spider.py: 引用items.py定义的item类,编写爬取程序提取item,最后返回item数据。
引用Spider类
为了创建一个spider,我们需要继承scrapy中的Spider类,并定义相应的属性和方法。
除了Spider这个最基础的类以外,scrapy还包含了CrawlSpider,XMLFeedSpider,CSVFeedSpider,SitemapSpider等几种爬虫类。
1 | # 引用Spider类 |
使用Selector选择器
为了从抓取回来的网页中提取数据,我们需要使用scrapy的Selector选择器,针对Selector选择器使用Xpath语法可以简单快速的提取数据。
Chrome中的XPath Helper拓展程序非常、非常、非常好用!!!
构造选择器
1 | from scrapy.selector import Selector |
xpath()
通过使用Selector的xpath()方法,传入xpath表达式,提取所需数据。
常用的xpath语法:
- //div : 选择所有的div标签
- //div[@type=’name’] : 选择所有type属性等于name的div标签
- //div[@type] : 提取所有div标签的type属性值
- //div/text() : 提取所有div标签的文本
extract(),re()
xpath()返回的结果仍然是selector list列表,我们需要将其转化为字符串list列表。
extract():不对提取结果做任何的处理,直接返回字符串列表;
re():针对提取结果传入正则表达式,只返回符合正则规则的字符串列表。
1 | # 以parse方法为例 |
进一步提取item数据
在引用Spider类的时候,我们已经定义了一个parse方法,并通过parse方法解析出了商品详情页的URL,并将URL的Request结果(也是response对象)丢给了我们自定义的parse_item方法。那么现在我们就需要通过parse_item方法进一步提取完整的item数据。
1 | def parse_item(self, response): |
心得
编写Spider程序最重要的是先梳理好网站结构和规则。
如果说spider语法是死的,那么网站结构和规则就是活的。有的网站是静态网页,有的是动态网页,而且每一个item数据的抓取规则也千差万别,我们需要细心耐心的去研究才能保证抓取过程的方便快速,抓取结果的准确。
That’s all.
Happy writing!