使用python scrapy框架抓取cnblog 的文章内容

scrapy 的文档请移驾到 http://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/install.html

1、准备工作 

安装python 、Spyder 、scrapy 如果想要数据直接入mysql 还需要安装python的 MySQLdb 依赖包

本人mac操作系统 安装MySQLdb的时候出现了些小问题  最后是重装了openssl 才通过的

Spyder 是编写python的ide 

2、新建项目 

cd /usr/local/var/www/python

执行 scrapy startproject myblog 则新建了一个名称为myblog 的项目,执行完成后 你的python文件夹就出现了myblog文件夹了

cnblog_spider.py 是后来我新建的 后缀.pyc 是执行python后的编译的文件 其他的都是执行创建项目后就自动生成的文件了 

3、编写爬虫脚本 cnblog_spider.py

分析cnblog的网站 使用scrapy shell  http://www.cnblogs.com/threemore/

使用google浏览器 找到你想要抓取的数据 话不多说 直接上代码,我抓取了cnblog文章的标题,链接 时间,文章的id,正文内容

# -*- coding: utf-8 -*-

from scrapy.spider import Spider
from scrapy.selector import Selector
from myblog.items import MyblogItem
import scrapy
import re
#SITE_URL = 'http://www.cnblogs.com/threemore/'


#抓取在cnblog中的文章
class CnblogSpider(Spider):
    #抓取名称 执行命令的时候后面的名称   scrapy crawl cnblog 中的cnblog 就是在这里定义的
    name ='cnblog'
    allow_domains = ["cnblogs.com"]
    
    
    #定义抓取的网址
    start_urls = [
        'http://www.cnblogs.com/threemore/'
    ]
    
    #执行函数
    def parse(self,response):
        sel = Selector(response)
        self.log("begins  % s" % response.url)
        article_list = sel.css('div.postTitle').xpath('a')
        
        #抓取列表里面的内容也地址后循环抓取列表的内容页面数据
        for article in article_list:
            url = article.xpath('@href').extract()[0]
            self.log("list article url: % s" % url)
        
            #继续抓取内容页数据
            yield scrapy.Request(url,callback=self.parse_content)
            
        #如果有下一页继续抓取数据
        next_pages = sel.xpath('//*[@id="nav_next_page"]/a/@href')
        
        if next_pages :
            next_page = next_pages.extract()[0]
            #print next_page
            self.log("next_page: % s" % next_page)
            #自己调用自己  类似php 函数的当中的递归
            yield scrapy.Request(next_page,callback=self.parse)
        
 
            
    #内容页抓取
    def parse_content(self,response):
        self.log("detail views: % s" % response.url)
        
        #定义好的item  只需要在items 文件中定义抓取过来的数据对应的字段
        item = MyblogItem()
        
        #xpath 寻找需要在页面中抓取的数据
        item['link'] =  response.url  
    
        #正则匹配出文章在cnblog中的id
        m = re.search(r"([0-9])+", item['link'])
        if m:
            item['aid'] = m.group(0)
        else:
            item['aid'] = 0;
        item['title'] = response.xpath('//*[@id="cb_post_title_url"]/text()').extract()[0]
        item['content'] = response.xpath('//*[@id="cnblogs_post_body"]').extract()[0]
        item['date'] = response.xpath('//*[@id="post-date"]').extract()
        #print item['content']
        yield item

4、数据入库

编写管道程序pipelines.py,管道就是存储数据使用的  爬虫文件最后yield 的item 会将数据给到pipelines.py 这个文件 

为了测试和正式环境的方便 我就配置了两份mysql的登陆信息

每次执行前 都将即将入库的数据表给清空了一次  防止重复采集 ,直接看代码

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

#需要在setting.py文件中设置ITEM_PIPELINES 将前面的注释打开配置成当前的文件即可
#当前的管道就是这么配置 'myblog.pipelines.MyblogPipeline': 300,


import MySQLdb,datetime


DEBUG = True

#定义测试环境和正式环境中的mysql  
if DEBUG:
    dbuser = 'root'
    dbpass = 'root'
    dbname = 'test'
    dbhost = '127.0.0.1'
    dbport = '3306'
else:
    dbuser = 'root'
    dbpass = 'root'
    dbname = 'test'
    dbhost = '127.0.0.1'
    dbport = '3306'

class MyblogPipeline(object):
    
    #初始化 链接数据库
    def __init__(self):
        
        self.conn = MySQLdb.connect(user=dbuser, passwd=dbpass, db=dbname, host=dbhost, charset="utf8", use_unicode=True)
    
        self.cursor = self.conn.cursor()
    
        self.cursor.execute('truncate table test_cnbog')        
    
        self.conn.commit()
    
    
    
    #执行sql语句 
    def process_item(self, item, spider):
        try:
            self.cursor.execute("""INSERT INTO test_cnbog (title, link, aid,content,date)  
                  VALUES (%s,%s,%s,%s,%s)""", 
                  (
                    item['title'].encode('utf-8'), 
                    item['link'].encode('utf-8'),
                    item['aid'],
                    item['content'].encode('utf-8'),
                    datetime.datetime.now(),
                  )
            )
            self.conn.commit()
        except MySQLdb.Error, e:
            
            print u'Error %d: $s' % (e.args[0],e.args[1])
        
        return item

5、配置setting.py

开启入库的配置 

找到 ITEM_PIPELINES 将前面的注释去掉  看到代码上面的注释的链接了么 直接访问看下是干啥的就行了  官方网站上看实例好像是将数据写入到monge里面去了

本人对monge 不熟悉 直接放到mysql去了 大致意思就是说pipelines.py 这个文件就是讲你采集的数据存放在什么地方

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'myblog.pipelines.MyblogPipeline': 300,
}

6、执行采集

在项目的文件夹下面执行 :scrapy crawl myblog

特意将crawl 拿百度翻译看了下 啥意思 原来就是“爬行”

最后展示下采集回来的数据

15条没有采集到数据 aid 程序就是拿正则随便处理了下  

 

转载于:https://www.cnblogs.com/threemore/p/5578372.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值