python3.4+pyspider爬58同城(二)

之前使用python3.4+selenium实现了爬58同城的详细信息,这次用pyspider实现,网上搜了下,目前比较流行的爬虫框架就是pyspider和scrapy,但是scrapy不支持python3,所以…

直接上代码,后面注解:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2016-04-17 16:54:22
# Project: tongcheng

from pyspider.libs.base_handler import *


class Handler(BaseHandler):
    crawl_config = {
                    'itag':'v226'  
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('
http://sz.58.com/pbdn/0/pn1/', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('#infolist a.t').items():
            if ('Mzhuanzhuan' not in str(each.attr.href)) and ('jump' not in each.attr.href):
                self.crawl(each.attr.href, callback=self.detail_page,fetch_type='js')

    @config(priority=2)
    def detail_page(self, response):

        return {
            "provice":response.doc('.crb_i a').eq(1).text(),
            "title":response.doc('.col_sub.mainTitle h1').text(),
             "data":response.doc(".time").text(),
            "views":response.doc("#totalcount").text(),
            "price":response.doc(".price.c_f50").text(),
            "condition":response.doc("#content > div.person_add_top.no_ident_top > div.per_ad_left > div.col_sub.sumary > ul > li:nth-child(2) > div.su_con > span").text(),
             "area":response.doc(".c_25d").find('a').text() if response.doc(".c_25d").find('a').text()!='' else "无",
             "seller":response.doc("#divContacter > ul > ul > li > a").text()
           
        }


crawl_config = { 'itag':'v226'  } #访问表头,useragent等请求信息都是在这里配置,其中itag表示版本的意思。pyspider有一个机制,如果在主页run一遍,那么每个请求的url都会有一个md5,标记这个任务已经结束,你再次点击run,pyspider不会再去请求同样的url,所以有时候我们修改完代码后,需要让任务执行一遍,重新将itag的版本号改一下就行。
image

on_start 函数类似java main函数,是运行代码的入口。

self.crawl('http://sz.58.com/pbdn/0/pn1/', callback=self.index_page) #意思是去请求'http://sz.58.com/pbdn/0/pn1/'网址,返回的内容交给index_page这个函数去处理。

index_page 函数,处理'http://sz.58.com/pbdn/0/pn1/'网址返回的内容,从代码我们可以看到,pyspider请求网站返回的对象都是用response为变量,而responce.doc()意思就是使用pyquery去处理网页返回的内容,所以responce.doc()该方法其实类似于:

    from pyquery import PyQuery as doc 将pyquery封装。

detail_page函数作用,就是获取网页的详细信息,获取下图区域,价格,浏览量等信息,并且返回一个字典

image

 

fetch_type='js' #pyspider调用phantomjs去渲染js,因为浏览量是js渲染,如果我们使用requests去请求,得不到该数据。pyspider已经封装了调用phantomjs函数库,所以我们在使用fetch_type时候,要保证安装了phantomjs。

@every(minutes=24 * 60)

这些装饰器作用是告诉pyspider多久自动执行一次,这样我们每天就可以获取最新的信息,此处代表每天执行一次。

@config(age=10 * 24 * 60 * 60)表示已经得到的数据保留十天,十天后弃掉

原文地址:https://www.cnblogs.com/huangweiping/p/5401603.html