cookielib模块基础学习

本文介绍如何使用Python的cookielib模块进行HTTP客户端Cookie的管理,包括Cookie的存储、读取和处理。并通过一个实例展示了如何利用Cookie进行网站登录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-

# python:2.x

__author__ = 'Administrator'

import cookielib

#主要用于处理http客户端的cookie

 

#cookielib.loadError在一个异常文件中失败加载,是IOEerror的子类

#cookielib.CookieJar用于存储cookie对象,此模块捕获cookie并在后续连接请教时重新发送,还可以用来处理包含cookie数据文件

#文档:https://docs.python.org/2/library/cookielib.html?highlight=cookielib#cookielib

"""

模块主要提供了这几个对象,CookieJar,FileCookieJar,MozillaCookieJar,LWPCookieJar。

CookieJar对象存储在内存中。

FileCookieJar一个对象实现吗CookiePolicy接口

MozillaCookieJar以加载和保存cookie的磁盘 Mozillacookies.txt使用的文件格式

LWPCookieJar可以加载和保存cookie到磁盘格式 兼容libwww-perl图书馆的Set-Cookie3文件格式

"""

import urllib2,urllib

cj=cookielib.CookieJar()

openner=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

r=openner.open('http://www.baidu.com')

print dir(r)

#例子:python 模拟获取获取osc openapi authorization_code:(网友提供)http://www.oschina.net/code/snippet_1244912_38304

 

class MyWeb():

    def __init__(self):

        self.header={ "User-Agent" : "Opera/8.0 (Macintosh; PPC Mac OS X; U; en)",

                       "Referer": "https://www.oschina.net/action/oauth2/authorize? \

                       response_type=code&client_id=LEW1z8ylZNHyiT7sB1kZ& \

                       redirect_uri=http://www.oschina.net/"}

        self.cookie=cookielib.LWPCookieJar()#可以加载和保存cookie到磁盘格式 兼容libwww-perl图书馆的Set-Cookie3文件格式

        self.cookie_support=urllib2.HTTPCookieProcessor(self.cookie)#处理HTTP cookie

        self.opener=urllib2.build_opener(self.cookie_support,urllib2.HTTPHandler)#生成一个opener,并通过该opener来访问URL;HTTPHandler:处理HTTP url

        urllib2.install_opener(self.opener)#用urllib2.install_opener(opener)把一些需要全局应用的opener加入urllib2中

    def post(self,posturl,dictdata):

            '''

        pass two arguement, posturl and postdict

        return urllib2.urlopen(request)

        '''

            posdata=urllib.urlencode(dictdata)

            request=urllib2.Request(posturl,posdata,self.header)#Request 中加入特定的 Headerurllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

            try:

                content=urllib2.urlopen(request)

            except Exception,e:

                print str(e)

            print type(content)

            return content

 

if __name__=='__main__':

    import hashlib

    web=MyWeb()

    password=''

    email=''

    password=hashlib.sha1(password).hexdigest()

    dictdata={

        'email':email,

        'pwd':password

        }

    url = "https://www.oschina.net/action/user/hash_login"

    urlAuth = "https://www.oschina.net/action/oauth2/authorize"

 

    dictdata2={

        'client_id': 'LEW1z8ylZNHyiT7sB1kZ', # 申请的client_id

                    'response_type': 'code',

                    'redirect_uri': 'http://www.oschina.net/',

                    'scope': 'blog_api,comment_api,favorite_api,message_api, \

                            news_api,notice_api,post_api,search_api, \

                            tweet_api,user_api,user_mod_api,',

                    'state': '',

                    'user_oauth_approval': 'true',

                    'email': email,

                    'pwd': password

    }

    web.post(url,dictdata)

    tmp=web.post(urlAuth,dictdata2)

    print tmp.url


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值