Python の Requests ライブラリを使った Web データの取得
2023年8月5日
このページでは、Python の Requests ライブラリを使った Web データの取得方法について、簡単にまとめています。
※検証環境は、Windows 10 Pro 64bit 版で行いました。
解説内容
1. Requests ライブラリのインストール
2. Web サーバーから HTML データを取得
3. Web サーバーから 画像 データを取得
1. Requests ライブラリのインストール
以下のコマンドを実行して、Requests ライブラリをインストールします。
コマンド:pip install requests
2. Web サーバーから HTML データを取得
Requests モジュールを使って、下記のURLのデータを取得し、HTMLファイルとして保存します。
URL:https://note.motnote.com/
HTML:index1.html、index2.html、index3.html
実行コマンド:python requests_html.py
# Requests モジュールを使ってWebサーバーからデータを取得し
# HTMLファイル(UTF-8)として保存する
import requests
try:
# Webリクエスト
res = requests.get('https://note.motnote.com/')
res.raise_for_status()
if res.status_code == 200:
# HTMLファイル出力 3パターン
with open("index1.html", "wb") as f:
f.write(res.content)
with open("index2.html", "wb") as f:
f.write(res.text.encode("utf-8"))
with open("index3.html", "wb") as f:
f.write(res.text.encode(res.encoding))
else:
print("Error status code : ", str(res.status_code))
except requests.exceptions.RequestException as e:
print("Exception : ", e)
実行後、HTMLファイル1~3が正常に保存されました。
3. Web サーバーから 画像 データを取得
Requests モジュールを使って、下記のURLの画像データを取得し、PNGファイルとして保存します。
URL:https://dev.motnote.com/devpg/requests/requests_dl.png
画像ファイル:requests_dl.png
実行コマンド:python requests_image.py
# Requests モジュールを使ってWebサーバーから画像データを取得し
# PNGファイルとして保存する
import requests
try:
# Webリクエスト
res = requests.get('https://dev.motnote.com/devpg/requests/requests_dl.png')
res.raise_for_status()
if res.status_code == 200:
# 画像ファイル出力
with open("requests_dl.png", "wb") as f:
f.write(res.content)
else:
print("Error status code : ", str(res.status_code))
except requests.exceptions.RequestException as e:
print("Exception : ", e)
実行後、画像ファイルが正常に保存されました。
以上で、Requests ライブラリの簡易検証は終了です。