如何在mechanize中手动为已设置cookies的会话添加更多cookies?

6 投票
1 回答
3842 浏览
提问于 2025-04-16 03:27

我有一个Python脚本,它可以抓取一个网页并获取一个cookie。我想在已经发送给服务器的cookie基础上,再添加一个新的cookie。这样在下次请求的时候,我就能同时使用原网页的cookie和我手动设置的cookie。

有没有办法做到这一点?我试过在mechanize中使用addheaders,但好像没有效果。

1 个回答

6

使用 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.

撰写回答