How to send cookies in a post request with the Python Requests library?
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
Send Cookie Using Python Requests
Yes. But make sure you call it "Cookie" (With capital C)
I always did it with a dict. Requests expects you to give a dict.
A string will give the following
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
TypeError: string indices must be integers, not str
python requests get cookies
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
How to add a cookie to the cookiejar in python requests library
I found out a way to do it by importing CookieJar, Cookie, and cookies. With help from @Lukasa, he showed me a better way. However, with his way I was not able to specify the "port_specified", "domain_specified", "domain_initial_dot" or "path_specified" attributes. The "set" method does it automatically with default values. I'm trying to scrape a website and their cookie has different values in those attributes. As I am new to all of this I'm not sure if that really matters yet.
my_cookie = {
"version":0,
"name":'COOKIE_NAME',
"value":'true',
"port":None,
# "port_specified":False,
"domain":'www.mydomain.com',
# "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
}
s = requests.Session()
s.cookies.set(**my_cookie)
Related Topics
A Good Way to Get the Charset/Encoding of an Http Response in Python
How to Compare String and Integer in Python
Cs50: Like Operator, Variable Substitution with % Expansion
How to Color Python Logging Output
How to Install 2 Anacondas (Python 2 and 3) on MAC Os
Reimport a Module While Interactive
Why Are There No ++ and -- Operators in Python
How to Convert a Time.Struct_Time Object into a Datetime Object
How to Login to a Website with Python
How to Save an Image Locally Using Python Whose Url Address I Already Know
How to Call a Shell Script from Python Code
Unicodedecodeerror When Redirecting to File
How to Use 'Else' in a List Comprehension
Remove File After Flask Serves It
Pyqt Gui Size on High Resolution Screens
Complexity of *In* Operator in Python
Why Does Sys.Exit() Not Exit When Called Inside a Thread in Python