pyspider使用实例

news/2024/7/19 11:17:58 标签: 爬虫, pyspider, 创建及使用

(注意:实例为爬取起点中文网 >地址:https://www.qidian.com/all)

创建项目:



创建后项目内容:


实例

    操作步骤:

        


数据库内容如下:

        使用mongodb数据库:



代码如下:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-06-14 17:11:18
# Project: qiushi

from pyspider.libs.base_handler import *
import pymongo, requests
from fake_useragent import UserAgent
import time

def get_proxy():
    return requests.get('http://localhost:5010/get/').text
    #由于代理池获取的免费代理,不稳定!因此后面的就不在使用代理,仅仅在这里把获取过程的封装函数放在这里!!
    
class Handler(BaseHandler):
    
    ua = UserAgent()
    headers = {
        'User-Agent': ua.random,
        # 'Host': 
        # 'Referer':
    }
    
    # 创建client和db
    client = pymongo.MongoClient('localhost')
    db = client['qidian']
    
    # 对于整个爬虫项目的全局配置:所有的self.crawl()在请求的时候都会加载这个配置。
    crawl_config = {
        'headers': headers,
        # 'proxy': get_proxy(),
        'itag': 'v0'
    }
    
    # 增量爬虫1:每天重新启动爬虫的时候,只爬取页面上更新的数据。(采用去重策略)
    # 增量爬虫2:url没有变化,数据更新了。(不能采用去重,每天都要重新爬取)
     # 项目启动首先进入的函数
    # @every: 用于设置定时爬取任务:可以是minutes, 也可以设置为seconds。
    @every(seconds=2 * 60)
    def on_start(self):
        # 初始爬取的url
        self.crawl('https://www.qidian.com/all', callback=self.index_page,validate_cert=False)
    

    # age: 主要是对任务url进行去重/过滤(根据taskid),每一个url有唯一的一个标识taskid,age是一个以秒为单位的时间点,
            #如果在这个时间范围内,遇到了相同的taskid,这个任务就会被丢弃。
    

    @config(age=60) 
    def index_page(self, response):
        # response.doc返回一个pyquery对象
        for each in response.doc('h4 > a').items():
            #fetch_type='js', js_script="":如果是javascript代码,需要在self.crawl()加入该参数
             self.crawl(each.attr.href, callback=self.detail_page, validate_cert=False)
            
        # 找到下一页
        # next_page = response.doc('.lbf-pagination-item-list > li:nth-of-type(9) > a')
        # self.crawl(next_page.attr.href, callback=self.index_page, validate_cert=False)
    
    
    # age的默认值是-1,永远不过期。
    @config(priority=2,age=60)
    def detail_page(self, response):
        # 从response中解析详情页的数据
        name = response.doc('h1 > em').text()
        author = response.doc('h1 a').text()
        tag = response.doc('.tag').text()
        info = response.doc('.intro').text()
        
        print(time.time())
        
        print(name)
        print(author)
        print(tag)
        print(info)
        return {
            "time": str(time.time()),
            "url": response.url,
            "title": response.doc('title').text(),
            "name":name,
            "author":author,
            "tag":tag,
            "info":info,
        }
    # on_result是固定的函数,只要一个函数中有return,就会自动调用这个函数。
    def on_result(self, data):
        # 将detail_page函数返回的结果,保存至mongodb中
        #print('接收到数据了.....',response['url'])
        if data == None:
            print('空')
        else:
            if self.db['q'].update_one({'name': data['name']}, {'$set': data}, True):
                print('数据保存成功')
            else:
                print('数据保存失败')
推荐一篇文章pyspider简易教程:网址>https://www.jianshu.com/p/36290e6acf45



http://www.niftyadmin.cn/n/1357036.html

相关文章

Redis 优缺点、安装与使用以及可视化工具RedisDesktopManager的安装使用(操作是爬取代理ip)

介绍 Redis:Redis是一个基于内存的高性能key-value数据库。 Redis数据支持类型:支持多种数据类型——string、list、hash(散列)、sets(集合)、sorted set(有序集合) Redis优点: 1.单线程,利用Redis队列技术…

CSS选择器——cssSelector定位方式详解

基本css选择器CSS选择器中&#xff0c;最常用的选择器如下&#xff1a; 选择器描述举例*通配选择器&#xff0c;选择所有的元素*<type>选择特定类型的元素&#xff0c;支持基本HTML标签h1.<class>选择具有特定class的元素。.class1<type>.<class>特定类…

global的作用以及使用方法

global的作用在编写程序的时候&#xff0c;如果想为一个在函数外的变量重新赋值&#xff0c;并且这个变量会作用于许多函数中时&#xff0c;就需要告诉python这个变量的作用域是全局变量。此时用global语句就可以变成这个任务&#xff0c;也就是说没有用global语句的情况下&…

selenium框架安装与使用(基本操作)——爬虫(selenium测试框架)

1、安装selenium&#xff1a; 2、下载浏览器驱动并放在python环境中&#xff08;此处为火狐浏览器&#xff09; 下载的推荐地址&#xff1a;https://blog.csdn.net/zhu940923/article/details/78105744 selenium测试框架在爬虫中的应用 网页中通过js渲染的数据&#xff0c;爬虫…

selenium窗口操作以及使用selenium定位iframe内部标签元素

1. 标签内部存在iframe&#xff0c;普通的方式无法直接定位到iframe内部的标签元素。需要 切换&#xff1b;2. 一个浏览器对象&#xff0c;存在多个标签选项卡。需要切换。打开多个页面以后&#xff0c;不会自动的切换界面&#xff0c;因此需要通过判断来切换定位的窗口&#x…

selenium操作实例(爬取本地的一本小说和淘宝搜索:笔记本电脑)以及进程池

本地小说&#xff1a;#!/usr/bin/env python # -*- coding:utf-8 -*-import time from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from multiprocessing import Poolclass XS(object):def __init__(self):self.options webdriver…

Python爬虫数据提取方式——正则表达式 re (附加实例:爬取csdn首页内容)附:表达式全集(正则表达式手册)

正则表达式手册地址&#xff1a;http://tool.oschina.net/uploads/apidocs/jquery/regexp.html 小点&#xff1a; 爬虫中主要使用—— (.*?) .*? .* re: 用于提取字符串内容的模块。 注意&#xff1a;特殊字符&#xff08;/,?等&#xff09;在正则中的含义…

python中group方法以及与groups的区别

python中的group方法group&#xff08;&#xff09;在正则表达式中用于获取分段截获的字符串&#xff0c;解释如下代码&#xff08;代码来自网络&#xff09;&#xff1a;import rea "123abc456"print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0) …