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。