获取返回的同步信息

凰tu
  • 228

想获取返回同步 Set-Cookie,这么获取. instance 类型

opener = urllib2.build_opener()

response=opener.open(url,data)
headers=response.headers

获取 headers 里面的 Set-Cookie .不是一个 instance 类型吗?

import urllib2,urllib,string,json,cookielib

def main():
    header={
        "User-Agent":r"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36"
    }
    url='http://my.kekenet.com/login'

    request = urllib2.Request(url,'',header)

    # HTTPCookieProcessor
    data=urllib.urlencode({
        "username":"catch001",
        "password":"futurelu9",
        "do":"login"
    })

    # "Accept-Language":"zh-CN,zh;q=0.8",
    # "Content-Type":"application/x-www-form-urlencoded"
    request.add_header("Accept-Language","zh-CN,zh;q=0.8")
    request.add_header("Content-Typee","application/x-www-form-urlencoded")

    # cookie=cookielib.MozillaCookieJar("d:/cookie.txt")
    # urllib2.HTTPCookieProcessor(cookie)
    opener = urllib2.build_opener()

    response=opener.open(url,data)
    headers=response.headers
    print headers,"**********",type(headers),"================",response.info,"================",response.msg

代码如上

打印结果是这样只的:

Server: nginx/1.4.4
Date: Fri, 03 Jun 2016 12:42:39 GMT
Content-Type: text/html;Charset=utf-8
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Set-Cookie: PHPSESSID=egl9r0lb5be5595lh0ijnq8ku2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: keke_auth=ebbehU2bz2NfZtRk889XILpIjUjaN7TswlIjAFuEu9%2FqXB11hZJR%2Fu%2BA%2BVEWCl8hUWvmlDmuzgDS2cF5SGkODz8; expires=Sat, 04-Jun-2016 12:42:39 GMT; path=/; domain=kekenet.com
Set-Cookie: zn_loginuser=catch001; expires=Sat, 03-Jun-2017 12:42:39 GMT; path=/; domain=kekenet.com
Set-Cookie: zn__refer=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=kekenet.com
 ********** <type 'instance'> ================ <bound method addinfourl.info of <addinfourl at 46689936 whose fp = <socket._fileobject object at 0x02C88870>>> ================ OK

我知道这样不合理的.

回复
阅读 4.1k
2 个回答
prolifes
  • 11.2k

你应该是想模拟登录,代码拿去

import requests

login_url = 'http://my.kekenet.com/login'
edit_url = 'http://my.kekenet.com/edit'

session = requests.Session()
data = {
    'username': '1',
    'password': 'futurelu9',
    'do': 'login'
}
r = session.post(login_url, data=data)
if r.text == u'<script>alert("登录失败.");window.history.back()</script>':
    print r.text
else:
    r = session.get(edit_url)
    print r.text

其实你已经在headers里获取到了,只是取法不对

response = opener.open(url, data)
headers = response.headers
if 'set-cookie' in headers:
    print headers['set-cookie']
宣传栏