python3下使用scrapy实现模拟用户登录与cookie存储 —— 基础篇(马蜂窝)

本文介绍了如何在Python3的Scrapy框架下实现模拟用户登录,包括登录步骤、注意事项以及如何存储和使用Cookie。文章通过马蜂窝网站为例,详细讲解了登录过程,并探讨了使用Cookie登录的优缺点。
摘要由CSDN通过智能技术生成

python3下使用scrapy实现模拟用户登录与cookie存储 —— 基础篇(马蜂窝)

1. 背景

2. 环境

  • 系统:win7
  • python 3.6.1
  • scrapy 1.4.0

3. 标准的模拟登陆步骤

  • 第一步:首先进入用户登录的页面,拿到一些登录所需的参数(比如说知乎网站,登陆页面里的 _xsrf)。
  • 第二步:将这些参数,和账户密码,一起post到服务器,登录。
  • 第三步:检查用户登录是否成功。
  • 第四步:如果用户登录失败,排查错误,重新启动登录程序。
  • 第五步:如果用户登录成功,按照正常流程爬取网站页面。
# 以马蜂窝网站登录为例,讲解如何模拟用户登录
# 保持登录状态,访问其他页面


# 爬虫文件:mafengwoSpider.py
# -*- coding: utf-8 -*-

import scrapy
import datetime
import re

class mafengwoSpider(scrapy.Spider):
    # 定制化设置
    custom_settings = {
        'LOG_LEVEL': 'DEBUG',       # Log等级,默认是最低级别debug
        'ROBOTSTXT_OBEY': False,    # default Obey robots.txt rules
        'DOWNLOAD_DELAY': 2,        # 下载延时,默认是0
        'COOKIES_ENABLED': True,    # 默认enable,爬取登录后的数据时需要启用。 会增加流量,因为request和response中会多携带cookie的部分
        'COOKIES_DEBUG': True,      # 默认值为False,如果启用,Scrapy将记录所有在request(Cookie 请求头)发送的cookies及response接收到的cookies(Set-Cookie 接收头)。
        'DOWNLOAD_TIMEOUT': 25,     # 下载超时,既可以是爬虫全局统一控制,也可以在具体请求中填入到Request.meta中,Request.meta['download_timeout']
    }

    name = 'mafengwo'
    allowed_domains = ['mafengwo.cn']
    host = "http://www.mafengwo.cn/"
    username = "13725168940"            # 蚂蜂窝帐号
    password = "aaa00000000"          # 马蜂窝密码
    headerData = {
        "Referer": "https://passport.mafengwo.cn/",
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
    }


    # 爬虫运行的起始位置
    # 第一步:爬取马蜂窝登录页面
    def start_requests(self):
        print("start mafengwo clawer")
        # 马蜂窝登录页面
        mafengwoLoginPage = "https://passport.mafengwo.cn/"
        loginIndexReq = scrapy.Request(
            url = mafengwoLoginPage,
            headers = self.headerData,
            callback = self.parseLoginPage,
            dont_filter = True,     # 防止页面因为重复爬取,被过滤了
        )
        yield loginIndexReq


    # 第二步:分析登录页面,取出必要的参数,然后发起登录请求POST
    def parseLoginPage(self, response):
        print(f"parseLoginPage: url = {response.url}")
        # 如果这个登录页面含有一些登录必备的信息,那么就在这个函数里面进行信息提取( response.text )

        loginPostUrl = "https://passport.mafengwo.cn/login/"
        # FormRequest 是Scrapy发送POST请求的方法
        yield scrapy.FormRequest(
            url = loginPostUrl,
            headers = self.headerData,
            method = "POST",
            # post的具体数据
            formdata = {
                "passport": self.username,
                "password": self.password,
                # "other": "other",
            },
            callback = self.loginResParse,
            dont_filter = True,
        )

    # 第三步:分析登录结果,然后发起登录状态的验证请求
    def loginResParse(self, response):
        print(f"loginResParse: url = {response.url}")

        # 通过访问个人中心页面的返回状态码来判断是否为登录状态
        # 这个页面,只有登录过的用户,才能访问。否则会被重定向(302) 到登录页面
        routeUrl = "http://www.mafengwo.cn/plan/route.php"
        # 下面有两个关键点
        # 第一个是header,如果不设置,会返回500的错误
        # 第二个是dont_redirect,设置为True时,是不允许重定向,用户处于非登录状态时,是无法进入这个页面的,服务器返回302错误。
        #       dont_redirect,如果设置为False,允许重定向,进入这个页面时,会自动跳转到登录页面。会把登录页面抓下来。返回200的状态码
        yield scrapy.Request(
            url = routeUrl,
            headers = self.headerData,
            meta={
                'dont_redirect': True,      # 禁止网页重定向302, 如果设置这个,但是页面又一定要跳转,那么爬虫会异常
                # 'handle_httpstatus_list': [301, 302]      # 对哪些异常返回进行处理
            },
            callback = self.isLoginStatusParse,
            dont_filter = True,
        )


    # 第五步:分析用户的登录状态, 如果登录成功,那么接着爬取其他页面
    # 如果登录失败,爬虫会直接终止。
    def isLoginStatusParse(self, response):
        print(f"isLoginStatusParse: url = {response.url}")

        # 如果能进到这一步,都没有出错的话,那么后面就可以用登录状态,访问后面的页面了
        # ………………………………
        # 不需要存储cookie
        # 其他网页爬取
        # ………………………………
        yield scrapy.Request(
            url = "https://www.mafengwo.cn/travel-scenic-spot/mafengwo/10045.html",
            headers=self.headerData,
            # 如果不指定callback,那么默认会使用parse函数
        )


    # 正常的分析页面请求
    def parse(self, response):
        print(f"parse: url = {response.url}, meta = {response.meta}")


    # 请求错误处理:可以打印,写文件,或者写到数据库中
    def errorHandle(self, failure):
        print(f"request error: {failure.value.response}")


    # 爬虫运行完毕时的收尾工作,例如:可以打印信息,可以发送邮件
    def closed(self, reason):
        # 爬取结束的时候可以发送邮件
        finishTime = datetime.datetime.now()
        subject = f"clawerName had finished, reason = {reason}, finishedTime = {finishTime}"
  • 登录成功的Log:
E:\Miniconda\python.exe E:/documentCode/scrapyMafengwo/start.py
2018-03-19 17:03:54 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapyMafengwo)
  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值