scrapy 结合 BeautifulSoup

简介: 创建Scrapy项目 首先,利用命令scrapy startproject csdnSpider创建我们的爬虫项目; 然后,在spiders目录下,创建CSDNSpider.py文件,这是我们主程序所在文件,目录结构如下: 定义Item 找到并打开items.py文件,定义我们需要爬取的元素: [python] view plain

创建Scrapy项目

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


定义Item

找到并打开items.py文件,定义我们需要爬取的元素:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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
  在CODE上查看代码片 派生到我的代码片
  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
  在CODE上查看代码片 派生到我的代码片
  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
  在CODE上查看代码片 派生到我的代码片
  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文件,查看爬取的博文信息:
目录
相关文章
|
4月前
|
XML API 数据格式
Beautiful Soup
Beautiful Soup 是一个用于从网页中提取数据的 Python 库。它可以帮助用户轻松地解析 HTML 和 XML 文档,并从中提取所需的信息。Beautiful Soup 基于 Python 的标准库,因此无需安装任何额外的依赖包即可使用。
45 7
|
7月前
|
XML C语言 数据格式
七、使用BeautifulSoup4解析HTML实战(一)
七、使用BeautifulSoup4解析HTML实战(一)
|
11月前
|
XML 数据格式 Python
|
数据采集 XML 移动开发
爬虫学习:Beautiful Soup的使用
一个强大的解析工具——Beautiful Soup,只需简单的几段代码就可以完成网页中某个信息的提取,一起来见识一下它的强大之处叭!
134 0
爬虫学习:Beautiful Soup的使用
|
Python
Beautiful Soup库的介绍
本节中将介绍如何使用 Beautiful Soup 来解析 HTML 以获取我们想要的信息。
76 0
|
XML 数据格式 Python
每日一模块——BeautifulSoup4
每日一模块——BeautifulSoup4