httplib2 cookie 问题


http = httplib2.Http()


 try:
    login_url = 'http://www.zimuzu.tv/User/Login/ajaxLogin'
    login_params = {'account': '[email protected]', 'password': '123456',
                    'remember': 1, 'url_back': 'http://www.zimuzu.tv/user/sign'}

    response, contents = http.request(login_url, method='POST', body=urlencode(login_params), headers=headers)
    headers['Cookie'] = response['set-cookie']  #保存cookie
    print('登陆返回状态', response['status'])
    contents_dict = eval(bytes.decode(contents))
    print(contents_dict)

    #签到页面
    response, contents = http.request(sign_url, headers=headers)
    #print('签到页面', response['status'])
    print(bytes.decode(contents))

为什么我这么写拿到的cookie不能访问下个页面,一直说我没登陆,是不是漏了什么东西啊?

python httplib2 cookie

efrik 9 years, 11 months ago

HTTP 响应头中的 Set-Cookie 的格式为:
Set-Cookie: ucn=center; Expires=Sat, 14 Jun 2025 13:34:31 GMT; Path=/;
HTTP 请求头中的 Cookie 的格式为:
Cookie: name=value; name2=value2

简单的获取并填写去过不是太合适的做法.
下面是我个人在日常使用中编写的一个 HttpClient 的类(自动处理Cookie).


 import cookielib, urllib, urllib2, socket

class HttpClient:
  __cookie = cookielib.CookieJar()
  __req = urllib2.build_opener(urllib2.HTTPCookieProcessor(__cookie))
  __req.addheaders = [
    ('Accept', 'application/javascript, */*;q=0.8'),
    ('User-Agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)')
  ]
  urllib2.install_opener(__req)

  def Get(self, url, refer=None):
    try:
      req = urllib2.Request(url)
      if not (refer is None):
        req.add_header('Referer', refer)
      return urllib2.urlopen(req, timeout=120).read()
    except urllib2.HTTPError, e:
      print e.read()
      return e.read()
    except socket.timeout, e:
      return ''
    except socket.error, e:
      return ''

  def Post(self, url, data, refer=None):
    try:
      req = urllib2.Request(url, urllib.urlencode(data))
      if not (refer is None):
        req.add_header('Referer', refer)
      return urllib2.urlopen(req, timeout=120).read()
    except urllib2.HTTPError, e:
      print e.read()
      return e.read()
    except socket.timeout, e:
      return ''
    except socket.error, e:
      return ''

  def Download(self, url, file):
    output = open(file, 'wb')
    output.write(urllib2.urlopen(url).read())
    output.close()

#  def urlencode(self, data):
#    return urllib.quote(data)

  def getCookie(self, key):
    for c in self.__cookie:
      if c.name == key:
        return c.value
    return ''

# vim : tabstop=2 shiftwidth=2 softtabstop=2 expandtab

使用方式:


 from HttpClient import HttpClient

http = HttpClient()

#POST
html = http.Post('https://aq.qq.com/cn2/change_psw/pc/pc_change_pwd_result',
(
  ('psw_old', PASS),
  ('psw', NewPass),
  ('psw_ack', NewPass),
  ('verifycode', vc),
  ('method', 2),
  ('sub_method', 0)
), Refer
)

#Get
html = http.Get("https://aq.qq.com/cn2/change_psw/pc/pc_change_pwd_way")

40只萨满 answered 9 years, 11 months ago

Your Answer