pyspider示例代码二:解析JSON数据

本系列文章主要记录和讲解pyspider的示例代码,希望能抛砖引玉。pyspider示例代码官方网站是http://demo.pyspider.org/。上面的示例代码太多,无从下手。因此本人找出一下比较经典的示例进行简单讲解,希望对新手有一些帮助。

示例说明:

pyspider爬取的内容通过回调的参数response返回,response有多种解析方式。
1、response.json用于解析json数据
2、response.doc返回的是PyQuery对象
3、response.etree返回的是lxml对象
4、response.text返回的是unicode文本
5、response.content返回的是字节码
本示例主要是利用response.json解析返回的json数据。其他返回类型示例见后续文章。

使用方法:

 

示例代码:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2016-06-21 13:57:13
# Project: duitang

from pyspider.libs.base_handler import *


class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('http://www.duitang.com/napi/friendship/fans/?start=0&limit=1000&user_id=116965', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in  response.json['data']['object_list']:
            id = each['id']
            self.crawl('http://www.duitang.com/napi/friendship/fans/?start=0&limit=1000&user_id='+str(id), callback=self.index_page)
            self.crawl('http://www.duitang.com/napi/people/profile/?user_id='+str(id), callback=self.detail_page)
        start = response.json['data']['next_start'] 
        total = response.json['data']['total']
        user = response.json['data']['visit_user']['user_id']
        if start < total:
            self.crawl('http://www.duitang.com/napi/friendship/fans/?start='+str(start)+'&limit=1000&user_id='+str(user),callback=self.index_page)

    
    @config(priority=2)
    def detail_page(self, response):
        return {
            "username": response.json['data']['username'],
             "id": response.json['data']['id']
        }

 

posted @ 2016-11-28 22:14  microman  阅读(3964)  评论(0编辑  收藏  举报