LoginSignup
25
24

More than 5 years have passed since last update.

Pythonでバイナリファイルを保存する

Last updated at Posted at 2015-01-27

自分はよく、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)

このように書けば実行できる。大変便利なのでスクリプト化しておくのも良いト思います。

25
24
2

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
25
24