scrapy实现全站抓取数据

1. scrapy.CrawlSpider

  scrapy框架提供了多种类型的spider,大致分为两类,一类为基本spider(scrapy.Spider),另一类为通用spider(scrapy.spiders.CrawlSpider、scrapy.spiders.XMLFeedSpider、scrapy.spiders.CSVFeedSpider、scrapy.spiders.SitemapSpider),并且值得注意的是,通用spider类型,均继承scrapy.Spider,那么我们在使用通用spider来抓取网页的时候,其解析方法名不能是parse(那样就重写了其父类Spider的parse方法,造成冲突)。

  为什么可以使用CrawlSpider进行全站抓取呢? 那么可以想像一下, 我们如果不使用它如何实现全站抓取, 首先我们需要解析一个网站的首页, 解析出其所有的资源链接(ajax方式或绑定dom事件实现跳转忽略),请求该页面所有的资源链接, 再在资源链接下递归地查找子页的资源链接,最后在我们需要的资源详情页结构化数据并持久化在文件中。这里只是简单的介绍一下全站抓取的大致思路,事实上,其细节的实现,流程的控制是很复杂的,所以scrapy封装了一个CrawlSpider,使得数据的爬取变得简单高效,因为它通过定义一组规则为跟踪链接提供了便利的机制。它可能不是最适合您的特定网站或项目,但它在几种情况下足够通用,因此您可以从它开始并根据需要覆盖它以获得更多自定义功能。

2. 重要属性

  A .     rules:这是一个(或多个)Rule对象的列表。每个都Rule 定义了爬网站点的特定行为。规则对象如下所述。如果多个规则匹配相同的链接,则将根据它们在此属性中定义的顺序使用第一个规则

     补充:class scrapy.spiders.Rulelink_extractorcallback = Nonecb_kwargs = Nonefollow = Noneprocess_links = Noneprocess_request = None 

     1.link_extractor是一个Link Extractor对象,它定义如何从每个已爬网页面中提取链接,可以是正则表达式,用于在跟进的时候筛选url(*重要*)

     2.callback是一个可调用的或一个字符串(在这种情况下,将使用来自具有该名称的spider对象的方法)为使用指定的link_extractor提取的每个链接调用。此回调接收响应作为其第一个参数,并且必须返回包含Item和/或 Request对象(或其任何子类)的列表(*重要*)

     3.cb_kwargs 是一个包含要传递给回调函数的关键字参数的dict。

     4.follow是一个布尔值,指定是否应该从使用此规则提取的每个响应中跟踪链接。如果callbackfollow默认值True,则默认为False(*重要*)

     5.process_links是一个可调用的,或一个字符串(在这种情况下,将使用来自具有该名称的spider对象的方法),将使用指定的每个响应从每个响应中提取的每个链接列表调用该方法link_extractor。这主要用于过滤目的。

     6.process_request 是一个可调用的,或一个字符串(在这种情况下,将使用来自具有该名称的spider对象的方法),该方法将在此规则提取的每个请求中调用,并且必须返回请求或None(以过滤掉请求)

  B .      ...................(Spider的allowed_domains、start_urls等

3. 实战需求

"""
爬取微信小程序社区所有教程(http://www.wxapp-union.com/portal.php?mod=list&catid=2),并以json格式存储在文件中
"""

4. 实现

  补充:新建CrawlSpider模板的爬虫的命令   scrapy genspider -t crawl wxappcrawl wxapp-union.com 

  settings.py

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'Accept-Language': 'en',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',

}

DOWNLOAD_DELAY = 3

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'wxapp.pipelines.WxappPipeline': 300,
}

  

  wxappcrawl .py

 1 # -*- coding: utf-8 -*-
 2 import scrapy
 3 from scrapy.linkextractors import LinkExtractor
 4 from scrapy.spiders import CrawlSpider, Rule
 5 from .. import items
 6 
 7 
 8 class WxappcrawlSpider(CrawlSpider):
 9     name = 'wxappcrawl'
10     allowed_domains = ['wxapp-union.com']
11     start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=1']
12 
13     '''
14     allow设置之后, 会在执行其父类(scrapy.Spider)的parse方法的时候, 提取response中符合这一正则的所有
15     url, 并添加到调度器下的请求队列(无重复)中
16     '''
17     rules = (
18         # 爬取每一页
19         Rule(LinkExtractor(allow=r'.+?mod=list&catid=2&page=\d'), follow=True),
20         # 爬取具体的文章页
21         Rule(LinkExtractor(allow=r'.+/article-\d+-\d+\.html'), callback='parse_article', follow=False),
22     )
23 
24     def parse_article(self, response):
25         '''
26         解析文章页,并返回实体
27         '''
28         article_title = response.xpath("//h1[@class='ph']/text()").get().strip()
29         article_author = response.xpath("//p[@class='authors']/a/text()").get().strip()
30         article_ctime = response.xpath("//p[@class='authors']/span[@class='time']/text()").get()
31         article_content_list = response.xpath("//td[@id='article_content']/*/text()").getall()
32         article_content = ''.join(article_content_list)
33 
34         yield items.WxappItem(
35             title = article_title,
36             author = article_author,
37             ctime = article_ctime,
38             content = article_content
39         )

  

  items.py

 1 # -*- coding: utf-8 -*-
 2 
 3 # Define here the models for your scraped items
 4 #
 5 # See documentation in:
 6 # https://doc.scrapy.org/en/latest/topics/items.html
 7 
 8 import scrapy
 9 
10 
11 class WxappItem(scrapy.Item):
12     # define the fields for your item here like:
13     # name = scrapy.Field()
14 
15     title = scrapy.Field()
16     author = scrapy.Field()
17     ctime = scrapy.Field()
18     content = scrapy.Field()

  

  pipelines.py

 1 # -*- coding: utf-8 -*-
 2 
 3 # Define your item pipelines here
 4 #
 5 # Don't forget to add your pipeline to the ITEM_PIPELINES setting
 6 # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
 7 
 8 from scrapy.exporters import JsonLinesItemExporter
 9 
10 class WxappPipeline(object):
11 
12     def __init__(self):
13         self.file = open('./wxapp.json', 'wb')
14         self.exporter = JsonLinesItemExporter(file=self.file, ensure_ascii=False, encoding='utf-8')
15 
16     def open_spider(self, spider):
17         pass
18 
19     def process_item(self, item, spider):
20         self.exporter.export_item(item)
21         return item
22 
23     def close_spider(self, spider):
24         self.file.close()

  

  run.py (在项目根目录下(与scrapy.cfg同级)新建启动爬虫的py文件)

1 from scrapy import cmdline
2 
3 cmdline.execute("scrapy crawl wxappcrawl".split())
4 
5 # cmdline.execute(['scrapy', 'crawl', 'wxappcrawl'])

  

  

哈哈·,收工!

  

  

猜你喜欢

转载自www.cnblogs.com/kisun168/p/10872784.html