首页 > 解决方案 > HTTPCookieProcessor 未将 cookie 添加到请求标头

问题描述

我正在尝试设置HTTP cookiePOST的网页。JSESSIONID尝试使用 自动设置此 cookie 时HTTPCookieProcessor,页面给出空白响应,当我打印出请求标头时,页面Cookie丢失。

代码:

@contextmanager
def get_opener():
    global proxies
    proxy = proxies.get()
    try:
        yield request.build_opener(
            request.HTTPCookieProcessor(),
            request.ProxyHandler(proxy)
            )
    finally:
        proxies.put(proxy)

def download(data, destination, tries=0):
    with get_opener() as opener:
        first_response = opener.open(request.Request('https://example.org/page.html'))
        print('First response info:')
        print(first_response.info())
        req = request.Request(Config.DOWNLOAD_URL, data=data, method='POST')
        response = opener.open(req)
        print('Second response:')
        print(response.info())
        print(response.read())
        print(req.headers)

输出:

First response info:
Set-Cookie: JSESSIONID=04CBF51EE096C4AD382D7D556CDF356D; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Language: en-US
Transfer-Encoding: chunked
Vary: Accept-Encoding
Date: Wed, 24 Jul 2019 05:37:05 GMT
Connection: close


Second response:
Content-Length: 0
Date: Wed, 24 Jul 2019 05:37:06 GMT
Connection: close


b''
{} # note no 'Cookie' header

我的印象是 cookie 会自动设置:

标签: pythoncookiespython-requests

解决方案


推荐阅读