Python2 爬虫(九) -- Scrapy & BeautifulSoup之再爬CSDN博文

点点圈 提交于 2019-11-28 01:36:53

我的Python3爬虫(五)博文使用utllib基本函数以及正则表达式技术实现了爬取csdn全部博文信息的任务。
上一篇Python3 爬虫(八) -- BeautifulSoup之再次爬取CSDN博文,我们就利用BeautifulSoup4重新实现了一次爬取csdn博文的任务。
那么,既然认识了Scrapy和BeautifulSoup,哪有不让它们合作一下的道理呢?不过,既然要使用Scrapy框架,我不得不又转战Ubuntu,使用Python2.7了。还是希望Python3能够尽快的支持Scrapy框架哦~
嘿嘿,我又不厌其烦的继续爬CSDN博文了,问我为什么尴尬?也没啥,只不过是想做下简单对比而已,当然你也可以爬别的东西啦~~~
这次博客首页主题没变,所以就不重复展示了,参看爬虫(八)即可。

创建Scrapy项目

首先,利用命令scrapy startproject csdnSpider创建我们的爬虫项目;
然后,在spiders目录下,创建CSDNSpider.py文件,这是我们主程序所在文件,目录结构如下:


定义Item

找到并打开items.py文件,定义我们需要爬取的元素:
[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. from scrapy.item import Item,Field  
  10.   
  11.   
  12. class CsdnspiderItem(scrapy.Item):  
  13.     # define the fields for your item here like:  
  14.     # name = scrapy.Field()  
  15.     pass  
  16.   
  17. class PaperItem(Item):  
  18.     title = Field() #博文标题  
  19.     link = Field() #博文链接  
  20.     writeTime = Field() #日志编写时间  
  21.     readers = Field() #阅读次数  
  22.     comments = Field() #评论数  

实现CSDNSpider

打开创建的CSDNSpider.py文件,实现代码:
[python] view plain copy
  1. # -*- coding: UTF-8 -*-  
  2. ############################################################################  
  3. # 程序:CSDN博客爬虫  
  4. # 功能:抓取我的CSDN全部博文  
  5. # 时间:2016/06/01  
  6. # 作者:yr  
  7. #############################################################################  
  8.   
  9. import scrapy, re, json, sys  
  10.   
  11. # 导入框架内置基本类class scrapy.spider.Spider  
  12. try:  
  13.     from scrapy.spider import Spider  
  14. except:  
  15.     from scrapy.spider import BaseSpider as Spider  
  16.   
  17. # 导入爬取一般网站常用类class scrapy.contrib.spiders.CrawlSpider和规则类Rule  
  18. from scrapy.contrib.spiders import CrawlSpider, Rule  
  19. from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor  
  20.   
  21. from bs4 import BeautifulSoup  
  22. from csdnSpider.items import PaperItem  
  23.   
  24. # 设置编码格式  
  25. reload(sys)  
  26. sys.setdefaultencoding('utf-8')  
  27.   
  28. add = 0  
  29. class CSDNPaperSpider(CrawlSpider):  
  30.     name = "csdnSpider"  
  31.     allowed_domains = ["csdn.net"]  
  32.     # 定义爬虫的入口网页  
  33.     start_urls = ["http://blog.csdn.net/fly_yr/article/list/1"]  
  34.     # 自定义规则  
  35.     rules = [Rule(LxmlLinkExtractor(allow=('/article/list/\d{,2}')), follow=True, callback='parseItem')]  
  36.   
  37.     # 定义提取网页数据到Items中的实现函数  
  38.     def parseItem(self, response):  
  39.         global add  
  40.         items = []  
  41.         data = response.body  
  42.         soup = BeautifulSoup(data, "html5lib")  
  43.         # 找到所有的博文代码模块  
  44.         sites = soup.find_all('div'"list_item article_item")  
  45.         for site in sites:  
  46.             item = PaperItem()  
  47.             # 标题、链接、日期、阅读次数、评论个数  
  48.             item['title'] = site.find('span'"link_title").a.get_text()  
  49.             item['link']= site.find('span'"link_title").a.get('href')  
  50.             item['writeTime'] = site.find('span'"link_postdate").get_text()  
  51.             item['readers'] = re.findall(re.compile(r'(.?)'), site.find('span'"link_view").get_text())[0]  
  52.             item['comments'] = re.findall(re.compile(r'(.?)'), site.find('span'"link_comments").get_text())[0]  
  53.             add += 1  
  54.             items.append(item)  
  55.         print("The total number:",add)  
  56.         return items  
从上述代码中,我们可看到网页元素的提取采用的BeautifulSoup库,而且我定义了一个全局变量add,来记录一共提取出来的博文总数,用来与输出结果对比,验证其正确性。

定义pipeline

找到并打开pipelines.py文件,添加代码:
[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. import scrapy  
  10. from scrapy import signals  
  11. import json, codecs  
  12.   
  13.   
  14. class CsdnspiderPipeline(object):  
  15.     def process_item(self, item, spider):  
  16.         return item  
  17.   
  18. class JsonWithEncodingCSDNPipeline(object):  
  19.     def __init__(self):  
  20.         self.file = codecs.open('papers.json''w', encoding='utf-8')  
  21.   
  22.     def process_item(self, item, spider):  
  23.         writeTime = json.dumps("日期:"+str(item['writeTime']),ensure_ascii=False) + "\n"  
  24.         title = json.dumps("标题:"+str(item['title']),ensure_ascii=False)+ "\n"  
  25.         link = json.dumps("链接:"+str(item['link']),ensure_ascii=False)+ "\n"  
  26.         readers = json.dumps("阅读次数:"+str(item['readers']),ensure_ascii=False)+ "\t"  
  27.         comments = json.dumps("评论数量:"+str(item['comments']),ensure_ascii=False)+ "\n\n"  
  28.         line = writeTime + title + link + readers + comments  
  29.         self.file.write(line)  
  30.         return item  
  31.   
  32.     def spider_closed(self, spider):  
  33.         self.file.close()  

修改设置文件

找到并打开setting.py文件:
[python] view plain copy
  1. # -*- coding: utf-8 -*-  
  2.   
  3. # Scrapy settings for csdnSpider project  
  4. #  
  5. # For simplicity, this file contains only the most important settings by  
  6. # default. All the other settings are documented here:  
  7. #  
  8. #     http://doc.scrapy.org/en/latest/topics/settings.html  
  9. #  
  10.   
  11. BOT_NAME = 'csdnSpider'  
  12.   
  13. SPIDER_MODULES = ['csdnSpider.spiders']  
  14. NEWSPIDER_MODULE = 'csdnSpider.spiders'  
  15.   
  16. # Crawl responsibly by identifying yourself (and your website) on the user-agent  
  17. #USER_AGENT = 'csdnSpider (+http://www.yourdomain.com)'  
  18. ITEM_PIPELINES = {  
  19.     'csdnSpider.pipelines.JsonWithEncodingCSDNPipeline'300,  
  20. }  
  21.   
  22. LOG_LEVEL = 'INFO'  

运行

在项目根目录下运行scrapy crawl csdnSpider,得到结果:



当前我的博文共有394篇,结果正确。打开项目根目录下的papers.json文件,查看爬取的博文信息:




易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!