python: urllib2 如何使用 urlopen 请求发送 cookie [英] python: urllib2 how to send cookie with urlopen request

查看:67
本文介绍了python: urllib2 如何使用 urlopen 请求发送 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

I am trying to do the following:

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

提前致谢

推荐答案

Cookie 只是另一个 HTTP 标头.

Cookie is just another HTTP header.

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

请参阅 urllib2 示例,了解如何将 HTTP 标头添加到您的要求.

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

有更多方法可以处理 cookie.一些模块,如 cookielib 试图表现得像网络浏览器 - 记住你得到了什么 cookie之前并在后续请求中自动再次发送.

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

这篇关于python: urllib2 如何使用 urlopen 请求发送 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆