【问题标题】:How to get cookies from urllib.request?如何从 urllib.request 获取 cookie?
【发布时间】:2014-10-02 07:53:33
【问题描述】:

如何从urllib.request 获取 cookie?

import urllib.request
import urllib.parse

data = urllib.parse.urlencode({
    'user': 'user',
    'pass': 'pass'
})
data = data.encode('utf-8')

request = urllib.request.urlopen('http://example.com', data)
print(request.info())

request.info() 返回 cookie 但不是很实用。

【问题讨论】:

  • 什么是“可用”的方式?
  • 您命名为 request,但这是一个 response 对象。这个问题很模糊,可以通过许多不同的方式来解决,但我们不知道你想要实现什么(因此“什么是可用的方式?”)

标签: python cookies python-3.x urllib


【解决方案1】:

response.info() 是一个dict 类型的对象。所以你可以解析你需要的任何信息。这是一个用python3编写的demo:

from urllib import request
from urllib.error import HTTPError

# declare url, header_params 

req = request.Request(url, data=None, headers=header_params, method='GET')
try:
    response = request.urlopen(req)

    cookie = response.info().get_all('Set-Cookie')
    content_type = response.info()['Content-Type']
except HTTPError as err:
    print("err status: {0}".format(err))
    return

您现在可以将 cookie 变量解析为您的应用程序要求。

【讨论】:

    【解决方案2】:

    我认为现在使用requests 包是一个更好的选择。试试这个在您访问时显示 google 设置 cookie 的示例代码:

    import requests
    
    url = "http://www.google.com"
    r = requests.get(url,timeout=5)
    if r.status_code == 200:
        for cookie in r.cookies:
            print(cookie)            # Use "print cookie" if you use Python 2.
    

    给予:

    Cookie NID=67=n0l3ME1Jl3-wwlH7oE5pvxJ_CfU12hT5Kh65wh21bvE3hrKFAo1sJVj_UcuLCr76Ubi3yxENROaYNEitdgW4IttL43YZGlf8xAPl1IbzoLG31KP5U2tiP2y4DzVOJ2fA for .google.se/
    
    Cookie PREF=ID=ce66d1288fc0d977:FF=0:TM=1407525509:LM=1407525509:S=LxQv7q8fju-iHJPZ for .google.se/
    

    【讨论】:

    • 我投了反对票,因为它没有回答问题 - 它的建议很好,但不是答案。
    • 我同意,这里没有答案。
    【解决方案3】:

    刚刚使用下面的代码从Python Challenge#17获取cookie,希望对你有帮助(正在使用Python 3.8):

    import http.cookiejar
    import urllib
    
    cookiejar = http.cookiejar.CookieJar()
    cookieproc = urllib.request.HTTPCookieProcessor(cookiejar)
    opener = urllib.request.build_opener(cookieproc)
    response = opener.open(url)
    for cookie in cookiejar:
        print(cookie.name, cookie.value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多