0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pythonのrequests.Sessionのサンプルコードメモ

Posted at

ネットアクセス系の機能にすごい苦手意識を持っていたのですがどうしても仕事で必要になってしまったため
ChatGTPにrequests.Sessionの使い方について聞いてみた

ChatGPT.txt
最初にアクセスしたいのは https://a_example.com/protected
ログインが必要な場合は https://b_example.com/login%a_example%com にリダイレクトされる
ログイン後、自動的に元のページ https://a_example.com/protected に戻ってくる

このようなクロスドメインログイン(SSOっぽい)+リダイレクト構成の場合でも、
requests.Session() を使えば大体は対応できます。
💡 補足
サーバーが 302 や 301 でリダイレクトする場合、requests は自動で追従します。
response.url を見れば、リダイレクト先の現在地がわかります。
CSRF トークンが必要な場合は BeautifulSoup などで HTML から抽出できます。

ボク「はぇ~こういうのがリダイレクトとかクロスドメインっていうのか…
言葉だけ知っていも実践で遭遇してそれと分からないのは
なんというかやっぱり素の頭が悪いのか、勉強しかたが悪いの、効率が悪いのか、なんかつらいな」

testlogin.py
import requests
from bs4 import BeautifulSoup

# セッションを作成(Cookie やリダイレクトの状態を維持)
session = requests.Session()

# 最初のアクセス:保護されたページ
initial_url = "https://a_example.com/protected"
response = session.get(initial_url)

# ここでログインページ(https://b_example.com/login%a_example%com)に自動リダイレクトされる
# レスポンスのURLや内容からログインページかどうかを判断
if "login" in response.url:
    print(f"リダイレクト先: {response.url}")

    # ログインページにある hidden フィールド(例:csrf_token)などを抽出(必要なら)
    soup = BeautifulSoup(response.text, 'html.parser')
    csrf_token = soup.find("input", {"name": "csrf_token"})["value"] if soup.find("input", {"name": "csrf_token"}) else ""

    # 認証情報とCSRFトークンを送信
    login_payload = {
        "username": "your_username",
        "password": "your_password",
        "csrf_token": csrf_token  # 必要に応じて
    }

    # ログイン先URL(通常は response.url)
    login_url = response.url
    login_response = session.post(login_url, data=login_payload)

    # ログイン後、自動的に a_example.com に戻っているかチェック
    if login_response.status_code == 200:
        print("ログイン成功。再度アクセスします。")
        final_response = session.get(initial_url)
        print(final_response.text)  # これが保護されたページのHTML

    else:
        print("ログイン失敗")
else:
    # すでに保護ページにアクセスできた場合
    print(response.text)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?