windows下使用python的scrapy爬虫框架,爬取个人博客文章内容信息

scrapy作为流行的python爬虫框架,简单易用,这里简单介绍如何使用该爬虫框架爬取个人博客信息。关于python的安装和scrapy的安装配置请读者自行查阅相关资料,或者也可以关注我后续的内容。
 
本文使用的python版本为2.7.9  scrapy版本为0.14.3 
 
1.假设我们爬虫的名字为vpoetblog
  在命令行下切换到桌面目录,输入startproject scrapy vpoetblog 如下图所示:
 
 命令执行成功后会在桌面生成一个名为vpoetblog的文件夹
该文件夹的目录为:
  scrapy.cfg

└─vpoetblog
      items.py
      pipelines.py
      settings.py
      __init__.py
    
    └─spiders
            __init__.py
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
这里我们要新建一些文件,最终的目录结构如下:
  scrapy.cfg
│  data.txt   //用于保存抓取到的数据
└─doubanmoive
      items.py  //用于定义抓取的item
      pipelines.py  //用于将抓取的数据进行保存
      settings.py
      __init__.py
    
    └─spiders
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
	   blog_spider.py  //主爬虫函数 用于定义抓取规则等
            __init__.py 
  • 1
  • 2
items.py内容如下:
[python] view plain copy
 
  1. # -*- coding: cp936 -*-  
  2. from scrapy.item import Item, Field  
  3.   
  4. class VpoetblogItem(Item):  
  5.     # define the fields for your item here like:  
  6.     # name = Field()  
  7.     article_name = Field() #文章名字  
  8.     public_time = Field()  #发表时间  
  9.     read_num = Field()     #阅读数量  


pipelines.py内容如下:
[python] view plain copy
 
  1. # -*- coding: utf-8 -*-  
  2. import sys  
  3. reload(sys)  
  4. sys.setdefaultencoding('utf-8')  
  5. from scrapy.exceptions import DropItem  
  6. from scrapy.conf import settings  
  7. from scrapy import log  
  8.   
  9. class Pipeline(object):  
  10.     def __init__(self):  
  11.         print 'abc'  
  12.   
  13.     def process_item(self, item, spider):  
  14.         #Remove invalid data  
  15.         #valid = True  
  16.         #for data in item:  
  17.           #if not data:  
  18.             #valid = False  
  19.             #raise DropItem("Missing %s of blogpost from %s" %(data, item['url']))  
  20.             #print 'crawl no data..... '  
  21.         #if valid:  
  22.         #Insert data into txt  
  23.         input = open('data.txt', 'a')  
  24.         input.write('article_name:'+item['article_name'][0]+'   ');  
  25.         input.write('public_time:'+item['public_time'][0]+'   ');  
  26.         input.write('read_num:'+item['read_num'][0]+'   ');  
  27.         input.close()  
  28.   
  29.         return item  


settings.py内容如下:
[python] view plain copy
 
  1. # Scrapy settings for vpoetblog project  
  2. #  
  3. # For simplicity, this file contains only the most important settings by  
  4. # default. All the other settings are documented here:  
  5. #  
  6. #     http://doc.scrapy.org/topics/settings.html  
  7. #  
  8.   
  9. BOT_NAME = 'vpoetblog'  
  10. BOT_VERSION = '1.0'  
  11.   
  12. SPIDER_MODULES = ['vpoetblog.spiders']  
  13. NEWSPIDER_MODULE = 'vpoetblog.spiders'  
  14.   
  15. ITEM_PIPELINES={  
  16.     'vpoetblog.pipelines.Pipeline':300  
  17. }  
  18.   
  19.   
  20. DOWNLOAD_DELAY = 2  
  21. RANDOMIZE_DOWNLOAD_DELAY = True  
  22. USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'  
  23. COOKIES_ENABLED = True  
blog_spider.py内容如下:
[python] view plain copy
 
  1. # -*- coding: utf-8 -*-  
  2. from scrapy.selector import HtmlXPathSelector  
  3. from scrapy.contrib.spiders import CrawlSpider,Rule  
  4. from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor  
  5. from vpoetblog.items import VpoetblogItem  
  6.   
  7. class MoiveSpider(CrawlSpider):  
  8.     name="vpoetblog"  
  9.     allowed_domains=["blog.csdn.net"]  
  10.     start_urls=["http://blog.csdn.net/u013018721/article/list/1"]  
  11.   
  12.     rules=[  
  13.         Rule(SgmlLinkExtractor(allow=(r'http://blog.csdn.net/u013018721/article/list/d+'))),  
  14.         Rule(SgmlLinkExtractor(allow=(r'http://blog.csdn.net/u013018721/article/details/d+')),callback="parse_item"),        
  15.     ]  
  16.   
  17.     def parse_item(self,response):  
  18.         sel=HtmlXPathSelector(response)  
  19.         item=VpoetblogItem()  
  20.         item['article_name']=sel.select('//*[@class="link_title"]/a/text()').extract()  
  21.         item['public_time']=sel.select('//*[@class="link_postdate"]/text()').extract()  
  22.         item['read_num']=sel.select('//*[@class="link_view"]/text()').extract()  
  23.   
  24.         return item  



运行命令如下:
 
运行截图如下:
原文地址:https://www.cnblogs.com/zxtceq/p/8534483.html