LoginSignup
0
0

Pythonを用いてURLからファイルをダウンロードする

Last updated at Posted at 2024-04-14

はじめに

Pythonと「Requests」ライブラリを用いて、定義したURLのファイルをダウンロードするコードを作成してみました。

サンプルコード

概要

ファイルのURLが作成されている「list.txt」ファイルを読み込んで、改行ごとのURLのファイルをダウンロードします。

コード例

「list.txt」ファイルは、以下のように改行でURLを区分します。

list.txtの例
https://www.~~~.com/~~~/sample_img1.png
https://www.~~~.com/~~~/sample_img2.png
https://www.~~~.com/~~~/sample_pdf1.pdf

Pythonのサンプルコードは、以下のように作成しました。

サンプルコード
import requests


def main():
    # テキストファイルからURLを取得する(改行で区分)
    with open("list.txt", "r") as txt_f:
        file_url_list = txt_f.read().splitlines()

    # 取得したURLごとにファイルをダウンロードする
    # file_urlの例:https://www.~~~.com/~~~/sample_img1.png
    for file_url in file_url_list:
        # URLを「/」に分割して、最後の文字列をファイル名にする
        # 例:sample_img1.png
        file_name = file_url.split("/")[-1]

        # ファイルをダウンロードする
        with open("./" + file_name, "wb") as w_f:
            response = requests.get(file_url, stream=True)

            if not response.ok:
                print(response)

            # chunk_sizeを1024(bytes)に設定する
            for chunk in response.iter_content(1024):
                if not chunk:
                    break

                w_f.write(chunk)


if __name__ == "__main__":
    main()
0
0
0

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
0
0