python: urllib2 如何使用 urlopen 请求发送 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3334809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:30:23  来源:igfitidea点击:

python: urllib2 how to send cookie with urlopen request

pythonurllib2

提问by Oleg Tarasenko

I am trying to use urllib2 to open url and to send specific cookie text to the server. E.g. I want to open site Solve chess problems, with a specific cookie, e.g. search=1. How do I do it?

我正在尝试使用 urllib2 打开 url 并将特定的 cookie 文本发送到服务器。例如,我想打开站点解决国际象棋问题,使用特定的 cookie,例如 search=1。我该怎么做?

I am trying to do the following:

我正在尝试执行以下操作:

import urllib2
(need to add cookie to the request somehow)
urllib2.urlopen("http://chess-problems.prg")

Thanks in advance

提前致谢

采纳答案by Messa

Cookie is just another HTTP header.

Cookie 只是另一个 HTTP 标头。

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

See urllib2 examplesfor other ways how to add HTTP headers to your request.

有关如何将 HTTP 标头添加到您的请求的其他方法,请参阅urllib2 示例

There are more ways how to handle cookies. Some modules like cookielibtry to behave like web browser - remember what cookies did you get previously and automatically send them again in following requests.

有更多方法可以处理 cookie。像cookielib这样的一些模块试图表现得像 Web 浏览器 - 记住您之前获得了哪些 cookie,并在随后的请求中自动再次发送它们。

回答by Marcelo Cantos

Use cookielib. The linked doc page provides examples at the end. You'll also find a tutorial here.

使用cookielib。链接的文档页面在最后提供了示例。您还可以在此处找到教程。

回答by Morten Jensen

Maybe using cookielib.CookieJarcan help you. For instance when posting to a page containing a form:

也许使用cookielib.CookieJar可以帮助你。例如,当发布到包含表单的页面时:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

编辑:

After Piotr's comment I'll elaborate a bit. From the docs:

在 Piotr 发表评论后,我将详细说明。从文档:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

CookieJar 类存储 HTTP cookie。它从 HTTP 请求中提取 cookie,并在 HTTP 响应中返回它们。CookieJar 实例在必要时自动使包含的 cookie 过期。子类还负责从文件或数据库中存储和检索 cookie。

So whatever requests you make with your CookieJarinstance, all cookies will be handled automagically. Kinda like your browser does :)

因此,无论您对CookieJar实例提出什么请求,所有 cookie 都将自动处理。有点像你的浏览器 :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.

我只能根据自己的经验发言,我 99% 的 cookie 用例是接收 cookie,然后需要在该会话中将其与所有后续请求一起发送。上面的代码处理了这个问题,而且它是透明的。

回答by Piotr Dobrogost

You might want to take a look at the excellent HTTP Python library called Requests. It makes every task involving HTTP a bit easier than urllib2. From Cookiessection of quickstart guide:

您可能想看看名为Requests的优秀 HTTP Python 库。它使涉及 HTTP 的每个任务都比 urllib2 容易一些。来自快速入门指南的Cookie部分:

To send your own cookies to the server, you can use the cookies parameter:

要将您自己的 cookie 发送到服务器,您可以使用 cookie 参数:

>>> cookies = dict(cookies_are='working')

>>> r = requests.get('http://httpbin.org/cookies', cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

回答by Solal

This answer is not working since the urllib2module has been split across several modules in Python 3. You need to do

此答案不起作用,因为该urllib2模块已拆分为 Python 3 中的多个模块。您需要执行

from urllib import request
opener = request.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")