首页 > 编程知识 正文

python用cookie登录,python 如何获取cookies

时间:2023-05-04 04:04:30 阅读:187636 作者:3514

I am trying to add a cookie to an existing cookiejar using the python requests 1.2.3 library. Every time I add the new cookie, the data in the jar is munged for the new cookie. Keys missing, Values missing or matched to incorrect Keys. I'm not sure if it's a Request library bug or I'm not sending the cookie correctly. I'm using the following code that is resulting in a bad cookie in cookiejar. Am I formatting the cookie correctly? Any ideas?

my_cookie = {

'domain':'www.mydomain.com',

'expires':None,

'name':'COOKIE_NAME',

'path':'/',

'value':'the cookie works',

'version':0

}

s = requests.Session()

requests.utils.add_dict_to_cookiejar(s.cookies, my_cookie)

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)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。