Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
29
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

Organization

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

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のドキュメントページ

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
29
Help us understand the problem. What are the problem?