Pythonでインターネットからファイルをダウンロードする方法

環境

  • Windows 10
  • Python 3.10.1

結論

urllibモジュールのurllib.request.urlretrieve()を使用する

実装

呼び出し側

urlオブジェクトを用意して、DownloadFileServiceに渡す
tests\test_download_file_service.py
import pytest
import os
from shared.Application.download_file_service import DownloadFileService
from shared.Domain.xurl import XUrl
from shared.Domain.xfile import XFile

@pytest.fixture
def setuped_xfile():
    x_url = XUrl(href="https://www.home-movie.biz/mov/hts-samp001.mp4")
    x_file = XFile(x_url)
    return x_file

def test_任意のファイルをダウンロードできること(setuped_xfile: XFile):
    download_path_to = "C:\\Users\\nishigaki\\Desktop\\"
    DownloadFileService().execute(
        x_file=setuped_xfile, download_path_to=download_path_to, extension=".mp4"
    )

    assert os.path.isfile("C:\\Users\\nishigaki\\Desktop\\hts-samp001.mp4")

shared\Application\download_file_service.py

  • urllib.request.urlretrieve()の第一引数にダウンロードするファイルのurlを、第二引数にダウンロード先のファイルパスとファイル名を結合させた文字列を渡す
from shared.Domain.xfile import XFile
import urllib.request
import urllib.parse
from shared.Domain.xstr import XStr

class DownloadFileService:
    def execute(self, x_file: XFile, download_path_to, extension):
        # 対象の拡張子が含まれていれば
        if XStr(x_file.get_file_name()).has_end(extension):

            try:
                urllib.request.urlretrieve(
                    x_file.get_url().get_href(),
                    download_path_to + x_file.get_file_name(),
                )
            except:
                print("ファイルのurlが不正です")

shared\Domain\xfile.py

import os
from shared.Domain.xurl import XUrl
from shared.Domain.xregex import XRegex
from shared.Application.check_regex_service import CheckRegexService
from shared.Domain.xstr import XStr

class XFile:
    def __init__(self, x_url: XUrl):
        self.x_url = x_url

    def get_url(self):
        return self.x_url

    # ファイル名を返します(クエリストリングは含まない)
    def get_file_name(self):

        file_name = CheckRegexService().execute(
            XRegex(".+?(?=\?)"), xstr=XStr(self.x_url.get_href())
        )

        return os.path.basename(file_name)

    def get_alt(self):
        return self.alt

    # 拡張子を返します
    def get_extension(self):
        return os.path.splitext(self.get_file_name())[1]

デスクトップに動画ファイルがダウンロードされていれば完了です

Python学習におすすめの書籍

独習Python/山田祥寛【3000円以上送料無料】
bookfan 1号店 楽天市場店
¥ 3,300(2022/02/05 17:20時点)
タイトルとURLをコピーしました