pyspider範例程式碼二:解析JSON資料

來源:互聯網
上載者:User

標籤:fan   created   方法   turn   mit   ase   start   import   call   

本系列文章主要記錄和講解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: duitangfrom 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‘]        }

 

pyspider範例程式碼二:解析JSON資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.