一般,我们HTTP抓包得到的Cookie位于Request Header中,格式如下:
Cookie: key1=val1; key2=val2; key3=val3
要使用该字符串发起HTTP请求,有几种方法:
- 使用httplib添加到headers中
- 使用cookielib创建CookieJar对象在urllib2中使用
- 使用requests模块
它们各有不足:
- httplib不会自动管理cookie(不会在后续的请求中自动添加、更新、删除过期)
- cookielib的处理过程稍复杂
- requests需要另安装
使用httplib直接添加cookie到header
如果不需要程序自己管理cookie,这个方法是极简单的。下面简单示例处理GET请求:
import httplib
import urlparse
def request(url, cookie=''):
ret = urlparse.urlparse(url) # Parse input URL
if ret.scheme == 'http':
conn = httplib.HTTPConnection(ret.netloc)
elif ret.scheme == 'https':
conn = httplib.HTTPSConnection(ret.netloc)
url = ret.path
if ret.query: url += '?' + ret.query
if ret.fragment: url += '#' + ret.fragment
if not url: url = '/'
conn.request(method='GET', url=url , headers={'Cookie': cookie})
return conn.getresponse()
if __name__ == '__main__':
cookie_str = 'tLargeScreenP=1; Authorization=Basic%20HereIsMySecret; subType=pcSub; TPLoginTimes=2'
url = 'http://192.168.1.253'
html_doc = request(url, cookie_str).read()
import re
print 'With Auth:', re.search('(.*?) ', html_doc, re.IGNORECASE).group(1)
html_doc = request(url).read()
print 'Without Auth:', re.search('(.*?) ', html_doc, re.IGNORECASE).group(1)
request函数就是全部的内容,测试IP 192.168.1.253是我房间的无线路由器。第一次HTTP请求带Cookie,第二次不带Cookie,返回的标题不一样:

