【发布时间】:2011-04-05 12:59:39
【问题描述】:
我有一个 python 脚本,它可以抓取一个页面并接收一个 cookie。我想将另一个 cookie 附加到正在发送到服务器的现有 cookie 中。这样在下一个请求时,我就有了来自原始页面的 cookie 以及我手动设置的那些。
无论如何要这样做?我在 mechanize 中尝试了 addheaders,但它被忽略了。
【问题讨论】:
我有一个 python 脚本,它可以抓取一个页面并接收一个 cookie。我想将另一个 cookie 附加到正在发送到服务器的现有 cookie 中。这样在下一个请求时,我就有了来自原始页面的 cookie 以及我手动设置的那些。
无论如何要这样做?我在 mechanize 中尝试了 addheaders,但它被忽略了。
【问题讨论】:
使用set_cookie 方法:
>>> import mechanize
>>> br=mechanize.Browser()
>>> br.set_cookie?
Definition: br.set_cookie(self, cookie_string)
Docstring:
Request to set a cookie.
Note that it is NOT necessary to call this method under ordinary
circumstances: cookie handling is normally entirely automatic. The
intended use case is rather to simulate the setting of a cookie by
client script in a web page (e.g. JavaScript). In that case, use of
this method is necessary because mechanize currently does not support
JavaScript, VBScript, etc.
The cookie is added in the same way as if it had arrived with the
current response, as a result of the current request. This means that,
for example, if it is not appropriate to set the cookie based on the
current request, no cookie will be set.
The cookie will be returned automatically with subsequent responses
made by the Browser instance whenever that's appropriate.
cookie_string should be a valid value of the Set-Cookie header.
For example:
browser.set_cookie(
"sid=abcdef; expires=Wednesday, 09-Nov-06 23:12:40 GMT")
Currently, this method does not allow for adding RFC 2986 cookies.
This limitation will be lifted if anybody requests it.
【讨论】: