python发送cookie请求_python中http请求中添加cookie支持

python3中构造http的Request需要用到urllib.request. 有时会用到cookie。

比如在访问网站首页得到cookie,通过下面代码添加cookie:

#install cookie

cj = cookiejar.CookieJar();

opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj));

urllib.request.install_opener(opener)

#build request for accessed url

homeReq = urllib.request.Request(

url = csdnAccessModuleUrl

)

homeReq.add_header('Accept', 'text/html, application/xhtml+xml, */*');

homeReq.add_header('Accept-Language', 'en-US')

homeReq.add_header('Accept-Encoding', 'gzip, deflate')

homeReq.add_header('Connection', 'Keep-Alive');

homeReq.add_header('Referer', 'http://passport.csdn.net/account/login?from='+urllib.parse.quote(moduleUrl))#http%3a%2f%2fwrite.blog.csdn.net%2f')

homeReq.add_header('User-Agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)');

#open access url

resp = urllib.request.urlopen(homeReq)

在上述代码运行后, 我们可以获取到cookie, 然后在后续登陆中用到此cookie。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值