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。

你可能感兴趣的:(http,python,cookie,自我心的)