如何使用 urllib 发送 cookie

How to send cookies with urllib

我正在尝试连接到一个网站,该网站要求您拥有特定的 cookie 才能访问它。对于这个问题,我们称 cookie 'required_cookie' 和值 'required_value'.

这是我的代码:

import urllib
import http.cookiejar

cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))

opener.addheaders = [('required_cookie', 'required_value'), ('User-Agent', 'Mozilla/5.0')]

urllib.request.install_opener(opener)

req = Request('https://www.thewebsite.com/')
webpage = urlopen(req).read()
print(webpage)

我是 urllib 的新手,所以请作为初学者回答我

要使用 urllib 执行此操作,您需要:

  • 构造一个Cookie object. The constructor isn't documented in the docs, but if you help(http.cookiejar.Cookie) in the interactive interpreter, you can see that its constructor demands values for all 16 attributes. Notice that the docs说,"It is not expected that users of http.cookiejar construct their own Cookie instances."
  • 使用 cj.set_cookie(cookie) 将其添加到 cookiejar。
  • 告诉 cookiejar 将正确的 headers 添加到带有 cj.add_cookie_headers(req) 的请求中。

假设您已正确配置策略,您就设置好了。

但这是一个巨大的痛苦。正如 urllib.request 的文档所说:

See also The Requests package is recommended for a higher-level HTTP client interface.

而且,除非您有充分的理由不能安装 requests,否则您真的应该这样做。 urllib 对于非常简单的情况是可以接受的,当你需要深入了解时它会很方便——但对于其他所有情况,requests 要好得多。

有了 requests,你的整个程序就变成了 one-liner:

webpage = requests.get('https://www.thewebsite.com/', cookies={'required_cookie': required_value}, headers={'User-Agent': 'Mozilla/5.0'}).text

…虽然几行可能更易读:

cookies = {'required_cookie': required_value}
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.thewebsite.com/', cookies=cookies, headers=headers)
webpage = response.text

借助 Kite 文档:https://www.kite.com/python/answers/how-to-add-a-cookie-to-an-http-request-using-urllib-in-python
您可以这样添加 cookie:

import urllib
a_request = urllib.request.Request("http://www.kite.com/")
a_request.add_header("Cookie", "cookiename=cookievalue")

或以不同的方式:

from urllib.request import Request
url = "https://www.kite.com/"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Cookie':'myCookie=lovely'})