requests を事前にインストールする。
pip install requests
Webサイトにアクセスするためのresponseオブジェクトを返す。他にpost(URL)もある。
どちらも辞書を引数paramsに渡し、パラメータを指定可能。
| text | 取得した文字列 |
| status_code | ステータスコード |
| url | アクセスしたURL |
| encoding | 文字コード。'utf-8'などを指定。 |
| content | 画像などバイナリデータ。 |
| json() | JSONに変換して取得 |
テキストを取得、表示
import requests url = 'http://www.dicre.com/python/time.cgi' r = requests.get(url) r.encoding = 'utf-8' # 文字コード設定 print(r.text) # テキスト
画像ダウンロード
import requests
url = 'http://www.dicre.com/python/cat.jpg'
r = requests.get(url)
f = open("cat.jpg","wb")
f.write(r.content)
f.close()
JSONダウンロード例
http://www.dicre.com/python/time.cgi
import requests url = 'http://www.dicre.com/python/time.cgi' r = requests.get(url) print(r.text) # テキスト
JavaScript Object Notation。JavaScriptの表記を元にしたオブジェクト表記法。
オブジェクトの例。Pythonの辞書とほぼ同じ。
{"name":"田中","age":30}
配列の例。Pythonのリストとほぼ同じ。
[10,20,30]
オブジェクト配列の例
[
{"name":"田中","age":30},
{"name":"鈴木","age":30},
{"name":"山本","age":30}
]
JSON文字列をjson()メソッドで変換し、オブジェクトは辞書、配列はリストとして処理が出来る。
例:以下のJSONデータが変数resに入っていた時
{
'date': "2020-08-26",
'time': "12:32:50"
}
import requests url = 'http://www.dicre.com/python/time.cgi' r = requests.get(url) res = r.json() print(res["date"]) print(res["time"])
http://www.dicre.com/python/nibai.php?num=5
URLの後に付ける ?num=5 のようなパラメータは辞書としてgetオプションのparams引数で渡すことができる。
import requests
url = 'http://www.dicre.com/python/nibai.php'
params = {'num':5}
r = requests.get(url,params = params)
print("URL=",r.url) # URL
print(r.text) # テキスト
さまざまなサイトがAPIの提供を行っている
Web API:アクセスするとJSONでデータを返す
※気象庁の非公開API
URL:
https://www.jma.go.jp/bosai/forecast/data/forecast/地域コード.json
※地域コード
http://www.jma.go.jp/bosai/common/const/area.json
import requests url = "https://www.jma.go.jp/bosai/forecast/data/forecast/430000.json" res = requests.get(url).json()
times = res[0]['timeSeries'][0]['timeDefines']
areas = res[0]['timeSeries'][0]['areas']
for area in res[0]['timeSeries'][0]['areas']:
print(area['area']['name'])
for i in range(3):
print(times[i], area['weathers'][i])
※気象庁の非公開API
URL:
https://www.jma.go.jp/bosai/amedas/data/map/年月日時分00.json
年月日時分は YYYYMMDDhhmm 形式
※観測所番号
https://www.jma.go.jp/bosai/amedas/const/amedastable.json
from datetime import datetime
now = datetime.now().strftime('%Y%m%d%H')
url = "https://www.jma.go.jp/bosai/amedas/data/map/" + now + "0000.json"
res = requests.get(url).json()
print(res['86141']['temp'])
https://www.googleapis.com/books/v1/volumes?q=isbn:9784088807232
import requests
import json
isbn = "9784088807232"
url = f"https://www.googleapis.com/books/v1/volumes?q=isbn:{isbn}"
response = requests.get(url)
data = response.json()
# 書誌情報を表示
if "items" in data:
for item in data["items"]:
# imageLinksがあるか?
if "imageLinks" not in item["volumeInfo"]:
continue
book_info = item["volumeInfo"]
title = book_info.get("title", "N/A")
authors = ", ".join(book_info.get("authors", []))
publisher = book_info.get("publisher", "N/A")
published_date = book_info.get("publishedDate", "N/A")
description = book_info.get("description", "N/A")
thumbnail = book_info.get("imageLinks", {}).get("thumbnail", "N/A")
# searchInfoがあるか?
text_snippet = item["searchInfo"].get("textSnippet", "N/A")
print(f"タイトル: {title}")
print(f"著者: {authors}")
print(f"出版社: {publisher}")
print(f"出版日: {published_date}")
print(f"説明: {description}")
print(f"サムネイル: {thumbnail}")
print(f"検索情報: {text_snippet}")
MediaTypeをMusic、StorefrontをJapan、TypeをSongsにしたURL
https://rss.marketingtools.apple.com/api/v2/jp/music/most-played/10/songs.json
import requests
url = 'https://rss.marketingtools.apple.com/api/v2/jp/music/most-played/10/songs.json'
res = requests.get(url).json()
results = res['feed']['results']
songs = []
for result in results:
title = result['name']
artist = result['artistName']
releaseDate = result['releaseDate']
artistUrl= result['artistUrl']
artworkUrl100 = result['artworkUrl']
url = result['url']
print(f"タイトル: {title}")
print(f"アーティスト: {artist}")
print(f"リリース日: {releaseDate}")
print(f"アーティストURL: {artistUrl}")
print(f"アートワークURL: {artworkUrl100}")
print(f"曲URL: {url}")
print("------------------------")
Twitter、Instagram、Amazon、楽天市場などが登録必要なWebAPIを提供している。