码迷,mamicode.com
首页 > 编程语言 > 详细

Python - cookielib [urllib2/requests]

时间:2015-01-23 18:24:40      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

cookie操作(读取,添加,删除,保存),结合urllib2和requests进行说明,此处只做局部演示,如果有疑问,请查阅: (Author: nixawk)

https://docs.python.org/2/library/cookielib.html
https://hg.python.org/cpython/file/2.7/Lib/cookielib.py

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

from cookielib import Cookie
from cookielib import CookieJar
from cookielib import FileCookieJar
from cookielib import LWPCookieJar
import urllib2
# Author : nixawk


def make_cookie(name, value, domain, path=‘/‘):
    return Cookie(version=0,
                  name=name,
                  value=value,
                  port=None,
                  port_specified=False,
                  domain=domain,
                  domain_specified=True,
                  domain_initial_dot=False,
                  path=path,
                  path_specified=True,
                  secure=False,
                  expires=None,
                  discard=False,
                  comment=None,
                  comment_url=None,
                  rest=None,
                  rfc2109=False)


def add_cookie(cookiejar, cookie):
    if isinstance(cookiejar, CookieJar):
        cookiejar.set_cookie(cookie)


def del_cookie(cookiejar, domain, path, cookiename):
    if isinstance(cookiejar, CookieJar):
        cookiejar.clear(domain, path, cookiename)


def get_cookies_from_response(url):
    cookiejar = CookieJar()

    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(cookiejar))
    opener.open(url)

    # add a new cookie or replace a old one
    newcookie = make_cookie(‘newcookie‘, ‘11111‘, ‘.baidu.com‘, ‘/‘)

    # remove a cookie
    cookiejar.clear(‘.baidu.com‘, ‘/‘, ‘newcookie‘)

    cookiejar.set_cookie(newcookie)

    import pdb
    pdb.set_trace()

    return cookiejar


def save_cookies_to_file1(url):
    cookiefile = ‘cookies.log‘

    filecookiejar = FileCookieJar(filename=cookiefile)

    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(filecookiejar))
    opener.open(url)

    # *******************************************
    # please read code cookielib [FileCookieJar]

    # filecookiejar.save(filename=cookiefile)
    # raise NotImplementedError()
    # ******************************************

    try:
        filecookiejar.save()
    except NotImplementedError as e:
        print e

    return filecookiejar


def save_cookies_to_file2(url):
    cookiefile = ‘cookies.log‘

    lwpcookiejar = LWPCookieJar(filename=cookiefile)

    opener = urllib2.build_opener(
        urllib2.HTTPCookieProcessor(lwpcookiejar))
    opener.open(url)

    lwpcookiejar.save()

    return lwpcookiejar

from pprint import pprint
pprint(get_cookies_from_response(‘http://www.baidu.com‘))

# pprint(save_cookies_to_file1(‘http://www.baidu.com‘))
# pprint(save_cookies_to_file2(‘http://www.baidu.com‘))

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import requests
# Author : nixawk


def make_request(method, url, headers={}, files=None, data={},
                 json=None, params={}, auth=None,
                 cookies=None, hooks={}):
    req = requests.Request(method, url, headers={},
                           files=None, data={},
                           json=None, params={},
                           auth=None,
                           cookies=None, hooks={})

    r = req.prepare()
    s = requests.Session()

    response = s.send(r)

    return response


def get_cookies_from_response(response):
    if hasattr(response, ‘cookies‘):
        return response.cookies

    return None


def save_cookies_to_file(url):
    pass


from pprint import pprint

response = make_request(‘GET‘, ‘http://www.baidu.com/‘)
cookies = get_cookies_from_response(response)

pprint(dir(cookies))


Python - cookielib [urllib2/requests]

标签:

原文地址:http://blog.csdn.net/nixawk/article/details/43058039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!