使用Scrapy来爬取自己的CSDN文章

前言

爬虫作为一中数据搜集获取手段,在大数据的背景下,更加得到应用。我在这里只是记录学习的简单的例子。大牛可以直接使用python的url2模块直接抓下来页面,然后自己使用正则来处理,我这个技术屌丝只能依赖于框架,在这里我使用的是Scrapy。

install

首先是python的安装和pip的安装。

sudo apt-get install python python-pip python-dev

然后安装Scrapy

sudo pip install Scrapy

在安装Scrapy的过程中,其依赖于cryptography,在自动安装cryptography编译的过程中,其缺少了libffi库,导致Scrapy安装失败。在安装过程中,库缺少是主要的问题,只要根据安装失败的提示,安装缺少的库就ok了。

sudo apt-get install libffi-dev

我们使用mongodb来保存我们爬取的数据。

sudo apt-get install mongodb

使用pymongo2.7.2

sudo pip install pymongo==2.7.2

过程

创建项目

使用下面的命令来创建一个项目

scrapy startproject csdn

csdn为项目名,其会产生如下结构的目录csdn

.

├── csdn

│ ├── init.py

│ ├── items.py

│ ├── pipelines.py

│ ├── settings.py

│ └── spiders

│ └── init.py

└── scrapy.cfg

2 directories, 6 files

我们接着在csdn目录下使用crawl模板来创建一个名为csdn_crawler的爬虫。

scrapy genspider csdn_crawler blod.csdn.net -t crawl

编写爬虫程序

在Scrapy中使用Item来保存一个爬取的项。我们的Item为CsdnItem,其包含两个域(Field),一个为title,另一个为url。

from scrapy.item import Item, Field

class CsdnItem(Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = Field()
    url = Field()
    pass

我们的爬虫

import scrapy
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule

from csdn.items import CsdnItem

class CsdnCrawlerSpider(CrawlSpider):
    name = ‘csdn_crawler‘
    allowed_domains = [‘blog.csdn.net‘]
    start_urls = [‘http://blog.csdn.net/zhx6044‘]

    rules = (
        Rule(LinkExtractor(allow=r‘article/list/[0-9]{1,20}‘), callback=‘parse_item‘, follow=True),
    )

    def parse_item(self, response):
        i = CsdnItem()
        #i[‘domain_id‘] = response.xpath(‘//input[@id="sid"]/@value‘).extract()
        #i[‘name‘] = response.xpath(‘//div[@id="name"]‘).extract()
        #i[‘description‘] = response.xpath(‘//div[@id="description"]‘).extract()
        i[‘title‘] = response.xpath(‘//*[@id="article_list"]/div[@class="list_item article_item"]/div[@class="article_title"]/h1/span/a/text()‘).extract()
        i[‘url‘] = response.xpath(‘//*[@id="article_list"]/div[@class="list_item article_item"]/div[@class="article_title"]/h1/span/a/@href‘).extract()
        return i

name为这个爬虫的名字,在开始运行爬虫的时候开始运行。

allowed_domains为爬虫针对的域名。

start_urls为爬虫开始的URL,后续的URL从这里开始。

rules为继续爬取的规则。这里的规则来之

下一页的链接为:article/list/xxxxxx为第几页。callback为有符合规则的链接时该调用的方法。

parse_item是爬虫默认处理页面内容的方法,只需重写即可。

下面最大的问题,就是怎么提取到文章的Title和URL。这里我们使用了Xpath,简单的来说这就通过规则匹配来提取到我们想要的内容。

下面,我们就要分析页面。

首先通过chromium的开发者工具找到我们需要的部分。

然后在

<a href="/zhx6044/article/details/45649045">
        qml+opencv(三)人脸检测与识别
        </a>

上右键选择Copy XPath,得到的是//*[@id=”article_list”]/div[1]/div[1]/h1/span/a,这个是第一条文章记录,第二条就是//*[@id=”article_list”]/div[2]/div[1]/h1/span/a,显然这个是不行的,我们不能改div[x]中的数值来索引条目,那么我们可以使用其class名来,它们都是一样的,所以就有了

   i[‘title‘] = response.xpath(‘//*[@id="article_list"]/div[@class="list_item article_item"]/div[@class="article_title"]/h1/span/a/text()‘).extract()
        i[‘url‘] = response.xpath(‘//*[@id="article_list"]/div[@class="list_item article_item"]/div[@class="article_title"]/h1/span/a/@href‘).extract()

text()得出的文本就是标题,@herf得到的就是链接,extract以unicode编码返回。

现在的到了CsdnItem,我们需要将他们保存起来,那么就需要用到PiepLine

import pymongo

from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log

class CsdnPipeline(object):
    def __init__(self):
        connection = pymongo.Connection(settings[‘MONGODB_SERVER‘], settings[‘MONGODB_PORT‘])
        db = connection[settings[‘MONGODB_DB‘]]
        self.collection = db[settings[‘MONGODB_COLLECTION‘]]

    def process_item(self, item, spider):
        valid = True
        for data in item:
            if not data:
                valid = False
                raise DropItem("Missing data!")
        if valid:
            #self.collection.update({‘url‘:item[‘url‘]}, dict(item), upsert = True)
            self.collection.insert(dict(item))
            log.msg("Article add to mongodb database!",level = log.DEBUG, spider = spider)
        return item

其process_item方法处理的Item就是csdn_crawler中得到的。

还有一个settings.py,我们在系统保存参数

BOT_NAME = ‘csdn‘
DOWNLOAD_DELAY = 5
SPIDER_MODULES = [‘csdn.spiders‘]
NEWSPIDER_MODULE = ‘csdn.spiders‘
ITEM_PIPELINES = {‘csdn.pipelines.CsdnPipeline‘:1000,}
MONGODB_SERVER="localhost"
MONGODB_PORT=27017
MONGODB_DB="csdn"
MONGODB_COLLECTION="article"

DOWNLOAD_DELAY避免一直爬去这个域名,导致其负载较大,但是对我们这样小规模的爬去,没什么作用。

运行

使用scrapy crawl csdn_crawler运行爬虫。

这是我们其中的一些输出

2015-05-13 21:05:01+0800 [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2015-05-13 21:05:02+0800 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-05-13 21:05:02+0800 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-05-13 21:05:02+0800 [scrapy] INFO: Enabled item pipelines: CsdnPipeline
2015-05-13 21:05:02+0800 [csdn_crawler] INFO: Spider opened
2015-05-13 21:05:02+0800 [csdn_crawler] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-05-13 21:05:02+0800 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-05-13 21:05:02+0800 [scrapy] DEBUG: Web service listening on 127.0.0.1:6080
2015-05-13 21:05:04+0800 [csdn_crawler] DEBUG: Crawled (200) <GET http://blog.csdn.net/zhx6044> (referer: None)
2015-05-13 21:05:09+0800 [csdn_crawler] DEBUG: Crawled (200) <GET http://blog.csdn.net/zhx6044/article/list/2> (referer: http://blog.csdn.net/zhx6044)
2015-05-13 21:05:09+0800 [csdn_crawler] DEBUG: Article add to mongodb database!
2015-05-13 21:05:09+0800 [csdn_crawler] DEBUG: Scraped from <200 http://blog.csdn.net/zhx6044/article/list/2>
    {‘title‘: [u‘\r\n        PHP\u4f7f\u7528CURL\u8fdb\u884cPOST\u64cd\u4f5c\u65f6\r\n        ‘,
               u‘\r\n        \u4ecestoryboard\u52a0\u8f7d\u89c6\u56fe\u63a7\u5236\u5668\r\n        ‘,
               u‘\r\n        PHP\u5f97\u5230POST\u4e0a\u6765\u7684JSON\u6570\u636e\r\n        ‘,
               u‘\r\n        Docker\r\n        ‘,
               u‘\r\n        Haproxy+nginx+php\r\n        ‘,
               u‘\r\n        php curl\r\n        ‘,
               u‘\r\n        \u5de5\u4f5c\u534a\u5e74\r\n        ‘,
               u‘\r\n        \u57fa\u4e8enginx_http_push_module\u6a21\u5757\u8ba9nginx\u53d8\u6210Comet Server\r\n        ‘,
               u‘\r\n        \u5728\u5185\u7f51\u67b6\u8bbe\u4e00\u4e2a\u53ef\u4f9b\u5916\u7f51\u767b\u5f55\u7684ftp\u670d\u52a1\u5668\r\n        ‘,
               u‘\r\n        REST,http,\u670d\u52a1\u5668\u5f00\u53d1\r\n        ‘,
               u‘\r\n        \u9634\u5dee\u9633\u9519\u53c8\u505a\u8d77linux\u6765\r\n        ‘,
               u‘\r\n        \u57fa\u4e8eTCP\u534f\u8bae\u7684\u89c6\u9891\u4f20\u8f93\r\n        ‘,
               u‘\r\n        \u5bb6\u4eba\u91cd\u75c5\u4ec0\u4e48\u5fc3\u60c5\u90fd\u6ca1\u4e86\r\n        ‘,
               u‘\r\n        opencv\u5b9e\u73b0\u8fb9\u7f18\u68c0\u6d4b\r\n        ‘,
               u‘\r\n        opencv\u5b9e\u73b0\u591a\u8def\u64ad\u653e\r\n        ‘],
     ‘url‘: [u‘/zhx6044/article/details/43418115‘,
             u‘/zhx6044/article/details/43418011‘,
             u‘/zhx6044/article/details/43417923‘,
             u‘/zhx6044/article/details/43417701‘,
             u‘/zhx6044/article/details/43240585‘,
             u‘/zhx6044/article/details/42804333‘,
             u‘/zhx6044/article/details/42646439‘,
             u‘/zhx6044/article/details/42040943‘,
             u‘/zhx6044/article/details/41051061‘,
             u‘/zhx6044/article/details/40789909‘,
             u‘/zhx6044/article/details/40592187‘,
             u‘/zhx6044/article/details/40016929‘,
             u‘/zhx6044/article/details/39970089‘,
             u‘/zhx6044/article/details/39256473‘,
             u‘/zhx6044/article/details/39033141‘]}
2015-05-13 21:05:09+0800 [csdn_crawler] DEBUG: Filtered duplicate request: <GET http://blog.csdn.net/zhx6044/article/list/3> - no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates)
2015-05-13 21:05:15+0800 [csdn_crawler] DEBUG: Crawled (200) <GET http://blog.csdn.net/zhx6044/article/list/14> (referer: http://blog.csdn.net/zhx6044)
2015-05-13 21:05:15+0800 [csdn_crawler] DEBUG: Article add to mongodb database!
2015-05-13 21:05:15+0800 [csdn_crawler] DEBUG: Scraped from <200 http://blog.csdn.net/zhx6044/article/list/14>

mongodb中的数据

整个代码可以在这里获得。

时间: 2024-08-22 18:12:22

使用Scrapy来爬取自己的CSDN文章的相关文章

使用Scrapy来爬取自己的CSDN文章 (2)

前言 前面讲到只是爬取了title和url,那么怎么爬取文章,其实原理是一样的. 过程 保存文章内容的Item 我们在item.py中添加一项,如下: class CsdnArticleItem(Item): title = Field() article = Field() pass 我们保存文章的题目和内容. 分析文章的链接 csdn是怎么来保存一篇文章的,我们来看一个url: http://blog.csdn.net/zhx6044/article/details/45698535 htt

selenium+scrapy完成爬取特定的知乎界面,比如我爬取的就是搜索“”“某某某东西”

这个地方非常感谢此篇作者的帮助 :http://blog.csdn.net/uselym/article/details/52525025 一.建立一个scrapy框架的爬虫 二.在spider中首先构造登录 二.使用response构造需要获取到的数据 三.在parse函数中返回request请求. 四.在scrapy.Request()中指定url="你需要爬取的界面" 总结:对于知乎的动态界面,scrapy爬虫爬取始终没有selenium模拟上下滑动获取的比较完整,望注意. 原文

Scrapy将爬取的段落整合为字符串

使用Scrapy框架爬取文章的时候,经常会遇到要爬取多个段落的问题,如果这个时候使用的是: text = response.xpath("......").extract() 那么会发现爬取下来的文章是以段落为单位的list,不方便直接展示. 这个时候可以将list转化为字符串,具体语法如下: content='\n'.join(text) 这样就可以把段落用换行符分割开来,方便直接展示. 原文地址:https://www.cnblogs.com/EdenChanIy/p/993647

03_使用scrapy框架爬取豆瓣电影TOP250

前言: 本次项目是使用scrapy框架,爬取豆瓣电影TOP250的相关信息.其中涉及到代理IP,随机UA代理,最后将得到的数据保存到mongoDB中.本次爬取的内容实则不难.主要是熟悉scrapy相关命令以及理解框架各部分的作用. 1.本次目标 爬取豆瓣电影TOP250的信息,将得到的数据保存到mongoDB中. 2.准备工作 需要安装好scrapy以及mongoDB,安装步骤这里不做赘述.(这里最好是先了解scrapy框架各个部分的基本作用和基础知识,这样方便后面的内容的理解.scrapy文档

如何提高scrapy的爬取效率

提高scrapy的爬取效率 增加并发: 默认scrapy开启的并发线程为32个,可以适当进行增加.在settings配置文件中修改CONCURRENT_REQUESTS = 100值为100,并发设置成了为100. 降低日志级别: 在运行scrapy时,会有大量日志信息的输出,为了减少CPU的使用率.可以设置log输出信息为INFO或者ERROR即可.在配置文件中编写:LOG_LEVEL = ‘INFO’ 禁止cookie: 如果不是真的需要cookie,则在scrapy爬取数据时可以进制coo

爬虫07 /scrapy图片爬取、中间件、selenium在scrapy中的应用、CrawlSpider、分布式、增量式

目录 爬虫07 /scrapy图片爬取.中间件.selenium在scrapy中的应用.CrawlSpider.分布式.增量式 1. scrapy图片的爬取/基于管道类实现 2. 中间件的使用 3. selenium在scrapy中的应用 4. CrawlSpider 5. 分布式 5. 增量式 爬虫07 /scrapy图片爬取.中间件.selenium在scrapy中的应用.CrawlSpider.分布式.增量式 1. scrapy图片的爬取/基于管道类实现 爬取流程: 爬虫类中将解析到的图片

爬取知名社区技术文章_分析_1

软件运行环境是什么? python 3.50                                      -- 解释器 scrapy库                                         -- 爬虫框架 pymsql库                                         -- 连接mysql数据库 pillow库                                           -- 下载图片 目标网站是什么

使用IP代理池和用户代理池爬取糗事百科文章

简单使用IP代理池和用户代理池的爬虫 import re import random import urllib.request as urlreq import urllib.error as urlerr #用户代理池 uapools = [ "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x

使用scrapy简易爬取豆瓣9分榜单图书并存放在mysql数据库中

注:大部分内容参考http://www.cnblogs.com/voidsky/p/5490798.html 首先创建一个项目douban9fen [email protected]:~/pachong$ scrapy startproject douban9fen New Scrapy project 'douban9fen', using template directory '/usr/local/lib/python2.7/dist-packages/scrapy/templates/p