Python pyspider 简单实用

官方文档:

 http://docs.pyspider.org/en/latest/

#ATTR_ENTRY_457060 .more > a#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-12-06 15:17:24
# Project: mty

from pyspider.libs.base_handler import *
import pymongo

class Handler(BaseHandler):
    crawl_config = {
    }
    # 创建mongo连接
    client = pymongo.MongoClient('127.0.0.1')
    db = client['mty']
    
    # 24 * 60分 执行
    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('https://www.tripadvisor.cn/Attractions-g294212-Activities-oa30-Beijing.html#FILTERED_LIST', callback=self.index_page)
    
    # 过期时间
    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('.more > a').items():
            self.crawl(each.attr.href, callback=self.detail_page)
        
        # 找到下一页
        next_href = response.doc('.next').attr.href
        self.crawl(next_href,callback=self.index_page)

    @config(priority=2)
    def detail_page(self, response):
        name = response.doc('h1').text()
        pls = response.doc('a > .reviewCount').text()
        address = response.doc('#taplc_location_detail_contact_card_ar_responsive_0 > div.contactInfo > div.detail_section.address > span').text()
        phone = response.doc('#taplc_location_detail_contact_card_ar_responsive_0 > div.contactInfo > div.contact > div.contactType.phone.is-hidden-mobile > div').text()
        kf_time = response.doc('.headerBL .header_detail').text()
        jj = response.doc('#component_3 > div > div:nth-child(2) > span:nth-child(1)').text()
        
        return {
            "url": response.url,
            "title": response.doc('title').text(),
            '名字':name,
            '评论数':pls,
            '地址':address,
            '手机':phone,
            '开放时间':kf_time,
            '简介':jj
        }
    
    # 自动调用
    def on_result(self,result):
        if result:
            self.save_mongo(result)
    
    def save_mongo(self,result):
        if self.db['beijing'].insert(result):
            print('保存到 mongo',result)

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值