フッターコンテンツにスキップ
PYTHONヘルプ

Python Requestsライブラリ(開発者向けのしくみ)

Pythonはそのシンプルさと読みやすさで広く称賛されており、WebスクレイピングやAPIとのやり取りを行う開発者の間で人気の選択肢となっています。そのようなやり取りを可能にする主要なライブラリの1つがPythonのRequestsライブラリです。 RequestsはPython用のHTTPリクエストライブラリで、HTTPリクエストを簡単に送信できます。 この記事では、PythonのRequestsライブラリの機能を掘り下げ、その使用法を実例とともに探り、IronPDFを紹介します。Requestsと組み合わせることで、WebデータからPDFを作成および操作する方法を示します。

Requestsライブラリの紹介

PythonのRequestsライブラリは、HTTPリクエストをよりシンプルで人間に優しいものにするために作成されました。 それは単純なAPIの背後にリクエストを行う複雑さを抽象化し、Web上のサービスとデータとのやり取りに集中できるようにします。 Webページを取得したり、REST APIとやり取りしたり、SSL証明書の検証を無効にしたり、サーバーにデータを送信したりする必要がある場合でも、Requestsライブラリが対応します。

主な機能
  1. シンプルさ: 使いやすく理解しやすい構文。
  2. HTTPメソッド: GET、POST、PUT、DELETEなど、すべてのHTTPメソッドをサポート。
  3. セッションオブジェクト: リクエスト間でクッキーを維持。
  4. 認証: 認証ヘッダーの追加を簡略化。
  5. プロキシ: HTTPプロキシのサポート。
  6. タイムアウト: リクエストのタイムアウトを効果的に管理。
  7. SSL検証: デフォルトでSSL証明書を検証。

Requestsのインストール

Requestsを使い始めるには、それをインストールする必要があります。 これはpipを使って行うことができます。

pip install requests
pip install requests
SHELL

基本的な使い方

ここにRequestsを使用してWebページを取得する簡単な例があります:

import requests

# Send a GET request to the specified URL
response = requests.get('https://www.example.com')

# Print the status code of the response (e.g., 200 for success)
print(response.status_code)

# Print the HTML content of the page
print(response.text)
import requests

# Send a GET request to the specified URL
response = requests.get('https://www.example.com')

# Print the status code of the response (e.g., 200 for success)
print(response.status_code)

# Print the HTML content of the page
print(response.text)
PYTHON

Python Requests Library (開発者向けにどのように機能するか): 図1 - HTTPリクエスト出力

URLでのパラメータの送信

多くの場合、URLにパラメータを渡す必要があります。 PythonのRequestsモジュールを使えば、それがparamsキーワードで簡単になります:

import requests

# Define the parameters to be sent in the URL
params = {'key1': 'value1', 'key2': 'value2'}

# Send a GET request with parameters
response = requests.get('https://www.example.com', params=params)

# Print the full URL including the parameters
print(response.url)
import requests

# Define the parameters to be sent in the URL
params = {'key1': 'value1', 'key2': 'value2'}

# Send a GET request with parameters
response = requests.get('https://www.example.com', params=params)

# Print the full URL including the parameters
print(response.url)
PYTHON

Python Requests Library (開発者向けにどのように機能するか): 図2 - Getリクエスト出力

JSONデータの処理

APIとのやり取りには通常JSONデータが含まれます。 Requestsは組み込みのJSONサポートによってこれを簡略化します:

import requests

# Send a GET request to retrieve JSON data
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

# Convert the JSON response to a Python dictionary
data = response.json()

# Print the JSON data
print(data)
import requests

# Send a GET request to retrieve JSON data
response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

# Convert the JSON response to a Python dictionary
data = response.json()

# Print the JSON data
print(data)
PYTHON

Python Requests Library (開発者向けにどのように機能するか): 図3 - JSON出力

ヘッダーの取り扱い

ヘッダーはHTTPリクエストにとって重要です。 このようにカスタムヘッダーをリクエストに追加できます:

import requests

# Define custom headers
headers = {'User-Agent': 'my-app/0.0.1'}

# Send a GET request with custom headers
response = requests.get('https://www.example.com', headers=headers)

# Print the response text
print(response.text)
import requests

# Define custom headers
headers = {'User-Agent': 'my-app/0.0.1'}

# Send a GET request with custom headers
response = requests.get('https://www.example.com', headers=headers)

# Print the response text
print(response.text)
PYTHON

Python Requests Library (開発者向けにどのように機能するか): 図4 - ヘッダー出力

ファイルのアップロード

Requestsはファイルのアップロードもサポートしています。 ここではファイルをアップロードする方法です:

import requests

# Define the files to be uploaded
files = {'file': open('report.txt', 'rb')}

# Send a POST request with the file
response = requests.post('https://www.example.com/upload', files=files)

# Print the status code of the response
print(response.status_code)
import requests

# Define the files to be uploaded
files = {'file': open('report.txt', 'rb')}

# Send a POST request with the file
response = requests.post('https://www.example.com/upload', files=files)

# Print the status code of the response
print(response.status_code)
PYTHON

Python Requests Library (開発者向けにどのように機能するか): 図5 - POSTリクエスト出力

Python用IronPDFの紹介

IronPDFは多用途なPDF生成ライブラリで、Pythonアプリケーション内でPDFを作成、編集、操作することができます。 特にHTMLコンテンツからPDFを生成する必要がある場合に役立ち、レポート、請求書、その他の配布が必要なドキュメントを作成するのに最適なツールです。

IronPDFのインストール

IronPDFをインストールするには、pipを使用します:

 pip install ironpdf

Python Requests Library (開発者向けにどのように機能するか): 図6 - IronPDF

IronPDFとRequestsの使用

RequestsとIronPDFを組み合わせることで、Webからデータを取得し、直接PDFドキュメントに変換することができます。 これはWebデータからのレポートの作成や、WebページをPDFとして保存する際に特に有効です。

ここにRequestsを使用してWebページを取得し、その後IronPDFを使用してPDFとして保存する方法の例があります:

import requests
from ironpdf import ChromePdfRenderer

# Fetch a web page
url = 'https://www.example.com'
response = requests.get(url)

if response.status_code == 200:
    # Extract the HTML content from the response
    html_content = response.text

    # Initialize the PDF renderer
    renderer = ChromePdfRenderer()

    # Render the HTML content as a PDF
    pdf = renderer.RenderHtmlAsPdf(html_content)

    # Save the generated PDF to a file
    pdf.save('output.pdf')
    print('PDF created successfully')
else:
    # Print an error message if the request was not successful
    print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
import requests
from ironpdf import ChromePdfRenderer

# Fetch a web page
url = 'https://www.example.com'
response = requests.get(url)

if response.status_code == 200:
    # Extract the HTML content from the response
    html_content = response.text

    # Initialize the PDF renderer
    renderer = ChromePdfRenderer()

    # Render the HTML content as a PDF
    pdf = renderer.RenderHtmlAsPdf(html_content)

    # Save the generated PDF to a file
    pdf.save('output.pdf')
    print('PDF created successfully')
else:
    # Print an error message if the request was not successful
    print(f'Failed to retrieve the webpage. Status code: {response.status_code}')
PYTHON

このスクリプトは、まずRequestsを使用して指定されたURLのHTMLコンテンツを取得します。 その後、IronPDFを使用してこのレスポンスオブジェクトのHTMLコンテンツをPDFに変換し、結果のPDFをファイルとして保存します。

Python Requests Library (開発者向けにどのように機能するか): 図7 - PDF出力

結論

Requestsライブラリは、Web APIとやり取りする必要があるPython開発者にとって不可欠なツールです。そのシンプルさと使いやすさは、HTTPリクエストを行うための標準的な選択肢となっています。 IronPDFと組み合わせることで、さらに多くの可能性が広がり、Webからデータを取得し、プロフェッショナルな品質のPDFドキュメントに変換することが可能です。 レポートの作成、請求書の発行、またはWebコンテンツのアーカイブを行う場合でも、RequestsとIronPDFの組み合わせは、PDF生成のニーズに対する強力なソリューションを提供します。

IronPDFのライセンスに関する詳細情報については、IronPDFのライセンスページを参照してください。 HTMLからPDFへの変換に関する詳細なチュートリアルもありますので、ぜひご覧ください。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。