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"

相关文章:

  • 2021-04-21
  • 2021-07-03
  • 2021-06-24
  • 2021-08-09
  • 2022-01-08
  • 2022-12-23
猜你喜欢
  • 2022-01-01
  • 2021-06-26
  • 2022-01-28
  • 2022-12-23
  • 2022-01-12
  • 2021-12-03
  • 2021-06-26
相关资源
相似解决方案