python添加自定义cookies

时间:2020-12-10 02:56:53
import cookielib,urllib2
class AddCookieHandler(urllib2.BaseHandler):
def __init__(self,cookieValue):
self.cookieValue = cookieValue
def http_request(self, req):
if not req.has_header('Cookie'):
req.add_unredirected_header('Cookie', self.cookieValue)
else:
cookie = req.get_header('Cookie')
req.add_unredirected_header('Cookie', self.cookieValue + '; ' + cookie)
return req

有时候仅仅使用python自带的cookielib不能满足我们的需求,这个时候我们就需要增加自定义的cookies了。网上找到相关文章,加以改进之后如上面所示,调用的时候可以如下。

cj = cookielib.CookieJar()
cookieProc = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookieProc, AddCookieHandler(sc))
urllib2.install_opener(opener)

如上面所示,其中的sc就是标准的cookies字符串,形如:"name=hehe;pass=gaoshangda"