在Python 3中读取Cookie值

时间:2019-01-22 12:55:08

标签: python

我有这个Python 2代码:

import requests
import json
import Cookie

USERNAME = "<user_name>"
PASSWORD = "<password>"
BACKEND = "https://blahblah.com"

# login will take orgId, email and password and return auth cookie for the user
def login(email, password):
    url = 'https://auth-v2.blahblah.com/auth/v1.0/login'
    data = json.dumps({'email':email, 'password': password})
    r = requests.post(url,data=data,allow_redirects=False)
    cookieHeaders = filter(lambda x: x.lower()=='set-cookie',r.headers.keys())
    if len(cookieHeaders)==0:
        return None
    bc = Cookie.BaseCookie(r.headers[cookieHeaders[0]])
    sess = 'sess='+bc.values()[0].value
    return sess

但是我无法将其正确转换为Python 3。

我只需要标题中的Set-Cookie值,但是过滤器函数或lambda的工作方式与Python 2中的不同。

Python 2中的filter()函数似乎返回了一个过滤器对象,该对象随后未通过len()检查并且也未通过“ bc =”行。

如何正确访问cookie值?

3 个答案:

答案 0 :(得分:1)

尝试使用“请求”模块和“ requests.Session”对象 Quick Start; Sessions

Refer this stackoverflow question for more detail

import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('http://httpbin.org/cookies')
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

print(s.cookies)
# RequestsCookieJar[Cookie(version=0, name='sessioncookie', value='123456789', port=None, port_specified=False, domain='httpbin.org', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]

答案 1 :(得分:0)

Python 2中的行为与Python3中的行为略有不同。

在Python 2中,以下工作正常:

foo = [1,2,3,4,5]
len(filter(lambda x: x>2, foo))

之所以有效,是因为type(filter(lambda x: x>2, foo))list

在Python 3中,您需要一个list构造函数:

foo = [1,2,3,4,5]
len(list(filter(lambda x: x>2, foo)))

实际上,Python 3 type(filter(lambda x: x>2, foo))<class 'filter'>

答案 2 :(得分:0)

您可以尝试内置cookie功能:

import requests

def login(email, password):
    url = 'https://wordpress.com/'
    data = {'email': email, 'password': password}
    r = requests.post(url, json=data, allow_redirects=False)

    print(r.cookies)
    print(r.cookies.get_dict())
    print(r.cookies.get_dict(domain='wordpress.com'))

    sess = 'sess={}'.format(r.cookies.get_dict()['wp_locale_test_group'])
    print(sess)
    return sess

将产生:

print(r.cookies)

<RequestsCookieJar[<Cookie SSE_blogger_ecommerce_20181217=test-a for .wordpress.com/>, <Cookie tk_ai=ZCGvpAX2VOVR5RO11DPzA1dm for .wordpress.com/>, <Cookie wp_locale_test_group=jan-2019 for wordpress.com/>]>

═══

print(r.cookies.get_dict())

{'SSE_blogger_ecommerce_20181217': 'test-a', 'tk_ai': 'ZCGvpAX2VOVR5RO11DPzA1dm', 'wp_locale_test_group': 'jan-2019'}

═══

print(r.cookies.get_dict(domain='wordpress.com'))

{'wp_locale_test_group': 'jan-2019'}

═══

print(sess)

sess=jan-2019