Scrapy框架利用CrawlSpider创建自动爬虫

一、适用条件

   可以对有规律或者无规律的网站进行自动爬取


 二、代码讲解 

 (1)创健scrapy项目

[python] view plain copy
  1. E:myweb>scrapy startproject mycwpjt  
  2. New Scrapy project 'mycwpjt', using template directory 'd:\\python35\\lib\\site-packages\\scrapy\\templates\\project', created in:  
  3.     D:\Python35\myweb\part16\mycwpjt  
  4. You can start your first spider with:  
  5.     cd mycwpjt  
  6.     scrapy genspider example example.com  
 (2) 创健爬虫

[python] view plain copy
  1. E:\myweb>scrapy genspider -t crawl weisuen sohu.com  
  2. Created spider 'weisuen' using template 'crawl' in module:  
  3.   Mycwpjt.spiders.weisuen  
(3)item编写

[python] view plain copy
  1. # -*- coding: utf-8 -*-  
  2.   
  3. # Define here the models for your scraped items  
  4. #  
  5. # See documentation in:  
  6. # http://doc.scrapy.org/en/latest/topics/items.html  
  7.   
  8. import scrapy  
  9.   
  10.   
  11. class MycwpjtItem(scrapy.Item):  
  12.     # define the fields for your item here like:  
  13.     name = scrapy.Field()  
  14.     link = scrapy.Field()  

(4)pipeline编写

[python] view plain copy
  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: http://doc.scrapy.org/en/latest/topics/item-pipeline.html  
  7.   
  8.   
  9. class MycwpjtPipeline(object):  
  10.     def process_item(self, item, spider):  
  11.         print(item["name"])  
  12.         print(item["link"])  
  13.         return item  

(5)settings设置

[python] view plain copy
  1. ITEM_PIPELINES = {  
  2.    'mycwpjt.pipelines.MycwpjtPipeline'300,  
  3. }  

(6)爬虫编写

[python] view plain copy
  1. # -*- coding: utf-8 -*-  
  2. import scrapy  
  3. from scrapy.linkextractors import LinkExtractor  
  4. from scrapy.spiders import CrawlSpider, Rule  
  5. from mycwpjt.items import MycwpjtItem  
  6.   
  7. #显示可用的模板              scrapy genspider -l  
  8. #利用crawlspider创建的框架  scrapy genspider -t crawl weisun sohu.com  
  9. #开始爬取                   scrapy crawl weisun --nolog  
  10.   
  11. class WeisunSpider(CrawlSpider):  
  12.     name = 'weisun'  
  13.     allowed_domains = ['sohu.com']  
  14.     start_urls = ['http://sohu.com/']  
  15.   
  16.     rules = (  
  17.         # 新闻网页的url地址类似于:  
  18.         # “http://news.sohu.com/20160926/n469167364.shtml”  
  19.         # 所以可以得到提取的正则表达式为'.*?/n.*?shtml’  
  20.         Rule(LinkExtractor(allow=('.*?/n.*?shtml'), allow_domains=('sohu.com')), callback='parse_item', follow=True),  
  21.     )  
  22.   
  23.     def parse_item(self, response):  
  24.         i = MycwpjtItem()  
  25.         #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()  
  26.         # 根据Xpath表达式提取新闻网页中的标题  
  27.         i["name"] = response.xpath("/html/head/title/text()").extract()  
  28.         # 根据Xpath表达式提取当前新闻网页的链接  
  29.         i["link"] = response.xpath("//link[@rel='canonical']/@href").extract()  
  30.         return i  

     CrawlSpider是爬取那些具有一定规则网站的常用的爬虫,它基于Spider并有一些独特属性

  • rules: 是Rule对象的集合,用于匹配目标网站并排除干扰
  • parse_start_url: 用于爬取起始响应,必须要返回ItemRequest中的一个。

      因为rulesRule对象的集合,所以这里介绍一下Rule。它有几个参数:link_extractorcallback=None、              cb_kwargs=Nonefollow=Noneprocess_links=Noneprocess_request=None
     其中的link_extractor既可以自己定义,也可以使用已有LinkExtractor类,主要参数为:

  • allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
  • deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。
  • allow_domains:会被提取的链接的domains。
  • deny_domains:一定不会被提取链接的domains。
  • restrict_xpaths:使用xpath表达式,和allow共同作用过滤链接。
三、结果显示

Scrapy框架利用CrawlSpider创建自动爬虫