Using Chrome's cookies in Python-Requests

隐身守侯 提交于 2019-12-06 18:24:40

问题


I'm trying to log in to the http://www.steampowered.com website using the cookies I've got from my Chrome session.

Once I've grabbed all the cookie table's data, using the command SELECT * FROM cookie WHERE host_key LIKE '%steam%' and the column names: PRAGMA table_info(cookie) and sorted through all the data with a list comprehension, I don't know how to pass it all to requests so that the cookies become usable.

The request's docs say you need to pass in a dict, ie cookies={'cookies':'are_working'} but then some of the keys names overwrite each other, since a few of the names are : Steam_Language, though they're different hosts.

edit: Just found How to add cookie to existing cookielib CookieJar instance in Python? which might help me out, but I don't know how to format the Chrome cookies for cookielib

My question is: How do I pass several different sites worth of cookies to requests?


回答1:


I created a module to load cookies from Firefox.

Example usage with requests:

import requests
import browser_cookie
cj = browser_cookie.firefox()
r = requests.get(url, cookies=cj)



回答2:


Keep in mind you're trying to do something that the HTTP specification intentionally tries to prevent you from doing (i.e. sending cookies to domains that they didn't come from). So you might be doomed from the start. And to make matters worse for you, I took a cursory look at the way steampowered implements login and you have your work cut out for you.

Back to your question...

Now, assuming your steampowered session cookies are valid (which they might not be based on the encryption, key sharing and captcha methods the login page performs), you might be able to login with the requests library by simply supplying a valid cookie dict as the docs state.

my_cookies = {'cookiename1': 'cookievalue1', 'cookiename2': 'cookievalue2'}
response = requests.get(
    'http://www.steampowered.com/mystuff',
    cookies=my_cookies)

Also, I don't know what data is stored in the databases you're getting the cookies from, but keep in mind that they might be storing all the metadata that comes along with a 'Set-Cookie' header (expiry, path, domain, etc). That's information the user-agent (Chrome, IE, the requests library, etc) uses to determine which cookies to send in a request but it is not included in the request. A 'Cookie' header only has name=value pairs. So that's all you need to supply in your cookie dict.

And, if you have two cookies with the same name, just pick one. Because in the end, most likely only one will be evaluated or else the server will simply return an error.



来源:https://stackoverflow.com/questions/11706046/using-chromes-cookies-in-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!