Scrapy学习实例(三)采集批量网页
优采云 发布时间: 2020-08-14 10:34原文可以听歌 Scrapy学习实例(三)采集批量网页
---
先来首火影压压惊 (`ω)
最开始接触 Rules是在Scrapy的文档上见到的,但是并看看懂这是哪些意思。接下来看他人的案例,有使用到Rules,便花了好多时间去了解。
解释:
Rule是在定义抽取链接的规则,上面的两条规则分别对应列表页的各个分页页面和详情页,关键点在于通过restrict_xpath来限定只从页面特定的部份来抽取接下来即将爬取的链接。
其实用我的话来说就是,一个是可以方便的进行翻页操作,二是可以采集二级页面,相当于打开获得详情页内容。所以若使用了 Rules,可以方便的帮助我们采集批量网页。
官方文档
CrawlSpider示例
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
# Extract links matching 'item.php' and parse them with the spider's method parse_item
Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
)
def parse_item(self, response):
self.logger.info('Hi, this is an item page! %s', response.url)
item = scrapy.Item()
item['id'] = response.xpath('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
return item
该spider将从的首页开始爬取,获取category以及item的链接并对前者使用 parse_item 方法。 对于每位item response,将使用XPath从HTML中提取一些数据,并使用它填充Item。实际应用
为了更好的理解,我们来瞧瞧实际案例中Rules怎样使用
豆瓣应用
rules = [Rule(LinkExtractor(allow=(r'https://movie.douban.com/top250\?start=\d+.*'))),
Rule(LinkExtractor(allow=(r'https://movie.douban.com/subject/\d+')),
callback='parse_item', follow=False)
]
如果接触过django,那么可以发觉这个规则与django的路由系统非常相像(django都早已忘完了 -_-!),其实这儿使用的正则匹配。
使用 r'\?start=\d+.*'来匹配翻页链接,如:
使用\d+来匹配具体影片的链接,如:
链家应用
爬虫的一般须要在一个网页上面爬去其他的链接,然后一层一层往下爬,scrapy提供了LinkExtractor类用于对网页链接的提取,使用LinkExtractor须要使用CrawlSpider爬虫类中,CrawlSpider与Spider相比主要是多了rules,可以添加一些规则,先看下边这个反例,爬取链家网的链接