Python 3でWebからファイルをダウンロードする


333

同じゲーム/アプリケーションの.jadファイルで指定されたURLを読み取ることにより、Webサーバーから.jar(java)ファイルをダウンロードするプログラムを作成しています。Python 3.2.1を使用しています

私はなんとかして、JADファイルからJARファイルのURLを抽出しました(すべてのJADファイルにはJARファイルへのURLが含まれています)。

関連する関数は次のとおりです。

def downloadFile(URL=None):
    import httplib2
    h = httplib2.Http(".cache")
    resp, content = h.request(URL, "GET")
    return content

downloadFile(URL_from_file)

ただし、上記の関数の型は文字列ではなくバイトでなければならないというエラーが常に発生します。URL.encode( 'utf-8')とbytes(URL、encoding = 'utf-8')を使用してみましたが、常に同じまたは同様のエラーが発生します。

だから基本的に私の質問は、URLが文字列型で格納されているときにサーバーからファイルをダウンロードする方法ですか?


4
@alvas、このための恵み?回答者はまだ(そしてかなり)SOでアクティブです。コメントを追加して質問しないのはなぜですか?
Bhargav Rao

8
Cosは、時間の試練が続く良い答えは授与する価値があります。また、他の多くの質問でもこれを実行して、回答が今日関連しているかどうかを確認する必要があります。特に、SOの回答の並べ替えがかなりおかしい場合は、古くなったり、最悪の場合でも、回答が上位になることがあります。
alvas、2016年

回答:


647

Webページのコンテンツを変数に取得する場合はread、次の応答のみを使用しurllib.request.urlopenます。

import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary

ファイルをダウンロードして保存する最も簡単な方法は、urllib.request.urlretrieve関数を使用することです。

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
urllib.request.urlretrieve(url, file_name)
import urllib.request
...
# Download the file from `url`, save it in a temporary directory and get the
# path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
file_name, headers = urllib.request.urlretrieve(url)

ただし、これurlretrieveレガシーと見なされ、非推奨になる可能性があることに注意してください(ただし、理由は不明です)。

したがって、これを行う最も正しい方法は、urllib.request.urlopen関数を使用してHTTP応答を表すファイルのようなオブジェクトを返し、を使用してそれを実際のファイルにコピーすることですshutil.copyfileobj

import urllib.request
import shutil
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

これが複雑すぎると思われる場合は、より単純にして、ダウンロード全体をbytesオブジェクトに保存し、それをファイルに書き込むことができます。ただし、これは小さなファイルに対してのみ有効です。

import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    data = response.read() # a `bytes` object
    out_file.write(data)

.gzその場で圧縮データを(そしておそらく他の形式で)抽出することは可能ですが、そのような操作ではおそらく、HTTPサーバーがファイルへのランダムアクセスをサポートする必要があります。

import urllib.request
import gzip
...
# Read the first 64 bytes of the file inside the .gz archive located at `url`
url = 'http://example.com/something.gz'
with urllib.request.urlopen(url) as response:
    with gzip.GzipFile(fileobj=response) as uncompressed:
        file_header = uncompressed.read(64) # a `bytes` object
        # Or do anything shown above using `uncompressed` instead of `response`.

7
ヘッダーから文字エンコーディングを取得するresponse.info().get_param('charset', 'utf-8')には、ハードコーディングの代わりに使用できますutf-8Content-Type
jfs

2
@OlehPrypinなぜoutfile.write(data)小さなファイルでしか機能しないのですか?
Startec

「urlretrieveはレガシーと見なされており、廃止される可能性があります」どこでそのアイデアを得ましたか?
Corey Goldberg

13
@Corey:ドキュメントから直接:「21.6.24。レガシーインターフェース次の関数とクラスは、Python 2モジュールurllibから移植されています(urllib2とは対照的です)。将来、廃止される可能性があります。」...そして私はオレの「理由がわからない」に同意します
cfi

@Oleh Prypin urllib.request.urlopen(url)を応答として使用し、open(file_name、 'wb')をout_fileとして使用する場合:shutil.copyfileobj(response、out_file)次に、catchステートメントでHTTPステータスコードを見つける方法ファイルが見つからなかったことを知るには?
Robert Achmann

146

requestsそのAPIは非常に簡単に開始できるため、HTTPリクエストに関連するものが必要なときはいつでもパッケージを使用します。

まず、インストール requests

$ pip install requests

次にコード:

from requests import get  # to make GET request


def download(url, file_name):
    # open in binary mode
    with open(file_name, "wb") as file:
        # get request
        response = get(url)
        # write to file
        file.write(response.content)

16

URLが文字列型で格納されている場合にサーバーからファイルをダウンロードする方法についての質問を正しく理解できたと思います。

以下のコードを使用して、ファイルをダウンロードしてローカルに保存します。

import requests

url = 'https://www.python.org/static/img/python-logo.png'
fileName = 'D:\Python\dwnldPythonLogo.png'
req = requests.get(url)
file = open(fileName, 'wb')
for chunk in req.iter_content(100000):
    file.write(chunk)
file.close()

こんにちは、私は、ファイルをダウンロードするためのコードの同じタイプを使用していますが、私はのような例外が直面しているいくつかの時間- 「のcharmap」コーデックができないエンコード文字「\ u010c」を.....あなたはそれで私を助けることができる
Joyson

10

ここでは、Python3でurllibのレガシーインターフェイスを使用できます。

次の関数とクラスは、Python 2モジュールurllib(urllib2ではなく)から移植されています。それらは将来的に廃止される可能性があります。

(2行のコード)

import urllib.request

url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")

9

そのために人気のあるダウンロードシェルツールであるwgetを使用できます。https://pypi.python.org/pypi/wget 宛先ファイルを開く必要がないため、これが最も簡単な方法です。ここに例があります。

import wget
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350'  
wget.download(url, '/Users/scott/Downloads/cat4.jpg') 

0

はい、間違いなくリクエストは、HTTPリクエストに関連する何かで使用するのに最適なパッケージです。ただし、着信データのエンコードタイプに注意する必要があります。以下は、違いを説明する例です


from requests import get

# case when the response is byte array
url = 'some_image_url'

response = get(url)
with open('output', 'wb') as file:
    file.write(response.content)


# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'

response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding

with open('output', 'w', encoding='utf-8') as file:
    file.write(response.content)

0

動機

画像を取得したいが、実際のファイルにダウンロードする必要がない場合もあります。

つまり、データをダウンロードしてメモリに保持します。

たとえば、機械学習手法を使用する場合は、番号(バーコード)で画像を認識できるモデルをトレーニングします。

モデルを使用してそれを認識できるように、いくつかのWebサイトにそれらの画像が含まれている場合、

これらの画像をディスクドライブに保存したくありません。

次に、以下の方法を試して、ダウンロードしたデータをメモリに保存し続けることができます。

ポイント

import requests
from io import BytesIO
response = requests.get(url)
with BytesIO as io_obj:
    for chunk in response.iter_content(chunk_size=4096):
        io_obj.write(chunk)

基本的に、@ Ranvijay Kumarに似ています

import requests
from typing import NewType, TypeVar
from io import StringIO, BytesIO
import matplotlib.pyplot as plt
import imageio

URL = NewType('URL', str)
T_IO = TypeVar('T_IO', StringIO, BytesIO)


def download_and_keep_on_memory(url: URL, headers=None, timeout=None, **option) -> T_IO:
    chunk_size = option.get('chunk_size', 4096)  # default 4KB
    max_size = 1024 ** 2 * option.get('max_size', -1)  # MB, default will ignore.
    response = requests.get(url, headers=headers, timeout=timeout)
    if response.status_code != 200:
        raise requests.ConnectionError(f'{response.status_code}')

    instance_io = StringIO if isinstance(next(response.iter_content(chunk_size=1)), str) else BytesIO
    io_obj = instance_io()
    cur_size = 0
    for chunk in response.iter_content(chunk_size=chunk_size):
        cur_size += chunk_size
        if 0 < max_size < cur_size:
            break
        io_obj.write(chunk)
    io_obj.seek(0)
    """ save it to real file.
    with open('temp.png', mode='wb') as out_f:
        out_f.write(io_obj.read())
    """
    return io_obj


def main():
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': 'statics.591.com.tw',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
    }
    io_img = download_and_keep_on_memory(URL('http://statics.591.com.tw/tools/showPhone.php?info_data=rLsGZe4U%2FbphHOimi2PT%2FhxTPqI&type=rLEFMu4XrrpgEw'),
                                         headers,  # You may need this. Otherwise, some websites will send the 404 error to you.
                                         max_size=4)  # max loading < 4MB
    with io_img:
        plt.rc('axes.spines', top=False, bottom=False, left=False, right=False)
        plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0))  # same of plt.axis('off')
        plt.imshow(imageio.imread(io_img, as_gray=False, pilmode="RGB"))
        plt.show()


if __name__ == '__main__':
    main()

-3
from urllib import request

def get(url):
    with request.urlopen(url) as r:
        return r.read()


def download(url, file=None):
    if not file:
        file = url.split('/')[-1]
    with open(file, 'wb') as f:
        f.write(get(url))
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.