Pythonで画像ファイルをダウンロードする方法

Pocket

メモとして残します。

通常の場合

urlにダウンロードしたいファイルのURLを指定します。
dst_pathに保存するパス(ファイル名まで)を指定します。

import urllib.request

def download_file(url, dst_path):
  req = urllib.request.Request(url = url)
  with urllib.request.urlopen(req) as response:
    data = response.read()
    with open(dst_path, mode = "wb") as f:
      f.write(data)

403 Forbiddenが出る場合

プログラムによるアクセスが禁止されている場合はブラウザからのアクセスであると偽装します。
headersでユーザーエージェントを指定します。

import urllib.request

def download_file(url, dst_path):
  headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0",}
  req = urllib.request.Request(url = url, headers = headers)
  with urllib.request.urlopen(req) as response:
    data = response.read()
    with open(dst_path, mode = "wb") as f:
      f.write(data)

[ 2020年9月14日 | カテゴリー: Python, デジタル ]

« | »

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

送信してください。


タグ

カテゴリー

最近の投稿

最近のコメント

固定ページ

アーカイブ

stabucky

写真

メタ情報