32
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python3のrequestsを使って画像を保存

Last updated at Posted at 2017-08-24

requests を用いて画像を保存

# -*- coding: utf-8 -*-

import requests
import shutil

def download_img(url, file_name):
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        with open(file_name, 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)

if __name__ == '__main__':
    download_img('ここにURLを書く', '保存したいファイル名を書く')

以下のような内容の編集リクエストを頂いたので合わせて載せておきます。(若干変更を加えました。)
こっちのほうがスマートかもしれません。

# -*- coding: utf-8 -*-

import requests

def download_img(url, file_name):
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        with open(file_name, 'wb') as f:
            f.write(r.content)

if __name__ == '__main__':
    download_img('ここにURLを書く', '保存したいファイル名を書く')

参考

urllib.request.urlretrieveについて

requests(クイックスタート)

shutilのドキュメントページ

32
31
1

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
32
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?