2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

国立国会図書館の書影APIを利用して書籍情報(書影)を取得する

Last updated at Posted at 2025-03-11

1.国立国会図書館APIについて

今回はpythonと書影APIを用いて書籍情報(書影)を取得します。

ISBNにたいして書影のデータが必ずあるとは限りませんので、注意が必要です。

以下のページなどを参考にしています。

以下のような形式でブラウザにアクセスすると任意のISBNの書影を取得することができます。".jpg"を最後に付けるのを忘れずに。
https://ndlsearch.ndl.go.jp/thumbnail/9784043898039.jpg

2.pythonによる書影の取得例

pythonで以下のように書影を取得することができます。

request.get()ではバイナリデータが返されるので、PILで読み込めるようにするためにBytesIO()を行います。
その後、PILで画像を表示します。

コードを実行すると画像が開かれます。

example01.py
import requests
from PIL import Image
from io import BytesIO

# ISBN
isbn = "9784043898039"

# NDLサムネイルAPIのURL
thumbnail_url = f"https://ndlsearch.ndl.go.jp/thumbnail/{isbn}.jpg"

# 画像を取得
response = requests.get(thumbnail_url)

# HTTPステータスが200なら画像を処理
if response.status_code == 200:
    img = Image.open(BytesIO(response.content))  # 画像データをPILで開く
    img.show()  # 画像を表示
else:
    print("画像が見つかりませんでした。")

3.pythonによる書影の取得 → 画像を保存

これでは実用的ではないので、書影を保存します。

エラー処理を加えました。

example02.py
import requests
from PIL import Image
from io import BytesIO

# ISBN
isbn = "9784043898039"

# NDLサムネイルAPIのURL
thumbnail_url = f"https://ndlsearch.ndl.go.jp/thumbnail/{isbn}.jpg"

try:
    # 画像を取得
    response = requests.get(thumbnail_url, timeout=5)
    response.raise_for_status()  # HTTPエラーなら例外を発生させる

    # 画像を処理
    img = Image.open(BytesIO(response.content))
    img.show()

    # 画像を保存
    save_path = f"{isbn}.jpg"
    img.save(save_path)
    print(f"画像を保存しました: {save_path}")

except requests.exceptions.RequestException as e:
    print(f"画像の取得に失敗しました: {e}")

except IOError:
    print("画像の処理に失敗しました。")

4.留意点

ISBNのリストなどを与えて、連続で書籍情報を取得することも可能になるかと思います。

ただし、ループ処理をする場合はサーバーに負荷をかけない配慮が必要になります。

下記の留意事項を遵守する必要があります。

多重アクセスの禁止は明確に示されているので、単一のリクエストを適切な時間間隔ごとにリクエストするのが望ましいでしょう。

5.まとめ

次回は取得した画像データに書籍情報を紐づけ、データベースに格納する手法について扱いたいと思います。

何かの足しになれば幸いです。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?