How can I use cookies in Python Requests? Ask Question

How can I use cookies in Python Requests? Ask Question

I am trying to log in to a page and access another link in the page.

I get a "405 Not Allowed" error from this attempt:

payload={'username'=<username>,'password'=<password>}
with session() as s:
    r = c.post(<URL>, data=payload)
    print(r)
    print(r.content)

I checked the post method details using Chrome developer tools and found a URL that appeard to be an API endpoint. I posted to that URL with the payload and it seemed to work; I got a response similar to what I could see in the developer.

Unfortunately, when trying to 'get' another URL after logging in, I am still getting the content from the login page. Why is the login not sticking? Should I use cookies? How?

ベストアンサー1

セッションオブジェクトを使うことができます。セッションオブジェクトはクッキーを保存してリクエストを行えるようにし、クッキーを処理します。

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

ドキュメント:https://requests.readthedocs.io/en/master/user/advanced/#セッションオブジェクト

また、Cookie データを外部ファイルに保存し、それを再読み込みして、スクリプトを実行するたびにログインしなくてもセッションを永続的に維持することもできます。

リクエスト (Python) クッキーをファイルに保存するにはどうすればいいですか?

おすすめ記事