1
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でセッションを利用する

Posted at

Pythonのrequestsでセッションを利用する

Webスクレイピングでセッションを保持する場合は、requests.Session() を利用するのが簡単です。

手順)

  1. requests.Session() でセッションを保持する
  2. get()、post()で操作を行う

ポイント)

  • withを利用することでセッションのクローズ忘れを防止できる

サンプル)

単純にセッションを利用してページの情報を取得したサンプルです

requests_test.py
import requests

def main():
    # セッションを利用する
    with requests.Session() as sec:

        # URLからページ情報を取得する
        url = r'https://pystyle.info/apps/scraping/'
        res = sec.get(url)

        # 失敗の場合は例外を発生する
        if not res.ok:
            raise f"ページの取得に失敗しました。status: {res.status_code}, reason: {res.reason}"
        else:
            print(res.status_code) # ステータスコード
            print(res.text) # 本文

if __name__ == '__main__':
    main()
1
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
1
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?