自分はよく、Python でとある壁紙サイトの壁紙画像を一括ダウンロードしたり、とあるフリー素材サイトの素材画像を一括ダウンロードしたりするんですが、その時にUNIX環境であれば、
import os
os.system("wget -O sample.jpg http://sample.org/sample.img")
みたいに wget で簡単にできたんですが、windows環境だとwgetは使えません。
なので、どうやってバイナリを保存するか調べてみました。
以下のようにやるみたいです。
import shutil
import requests
URL = "http://sample.org/sample.img"
res = requests.get(URL,stream=True)
with open(filepath,"wb") as fp:
shutil.copyfileobj(res.raw,fp)
上記のように、requests モジュールの Response
オブジェクトにある raw
(urllib3を使ったHTTPResponseオブジェクト)を、
shutil モジュールの copyfileobj
関数を使って ターゲットのファイルオブジェクトにコピーすることで保存する 、という形式です。
これを用いれば、たとえばとある壁紙サイトから画像ファイルを一括ダウンロードしたいときは、
import shutil
import requests
from BeautifulSoup import BeautifulSoup
URL = "http://sample.org/"
targets = []
soup = BeautifulSoup(requests.get(URL).text)
for link in soup.findAll("a"):
if link.get("href").endswith(".jpg"):
targets.append(link.get("href"))
for target in targets:
res = requests.get(target)
with open(target.split("/")[-1], "wb") as fp:
shutil.copyfileobj(res.raw,fp)
このように書けば実行できる。大変便利なのでスクリプト化しておくのも良いト思います。