Python을 사용하여 HTTP를 통해 파일을 다운로드하려면 어떻게 하나요?

일정에 따라 웹 사이트에서 MP3를 다운로드하는 데 사용하는 작은 유틸리티가 있는데, 이 유틸리티는 팟캐스트 XML 파일을 생성/업데이트하여 iTunes에 분명히 추가했습니다.

XML 파일을 생성/업데이트하는 텍스트 처리는 Python으로 작성되었습니다. 그러나 실제 MP3를 다운로드하기 위해 Windows '.bat'파일 내부의 wget을 사용합니다. 하지만 전체 유틸리티를 파이썬으로 작성하는 것을 선호합니다.

하지만 실제로 파이썬으로 파일을 다운로드하는 방법을 찾는 데 어려움을 겪었기 때문에 wget에 의존했습니다.

그렇다면 파이썬을 사용하여 파일을 다운로드하려면 어떻게 해야 할까요?

질문에 대한 의견 (2)

한 번 더 using ['우를레리브'] [1]:

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

('3' 와 '를 사용하여 파이썬으로 우를리발리퀘스트 임포트합니다 우를리발리퀘스트리우를레리브')

그러나 다른 수신기마다 &quot progressbar";

import urllib2

url = "http://download.thinkbroadband.com/10MB.zip"

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()

[1]: http://docs.python.org/2/library/urllib.html # 우를리발우를레리브

해설 (14)
해결책

Python 2에서는 표준 라이브러리와 함께 제공되는 urllib2를 사용합니다.

import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()

이것은 오류 처리를 제외한 가장 기본적인 라이브러리 사용 방법입니다. 헤더 변경과 같은 더 복잡한 작업을 수행할 수도 있습니다. 문서는 여기에서 찾을 수 있습니다.

해설 (6)

2012년, list. 파이썬 요청률 라이브러리란

>>> import requests
>>> 
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760

요청률 이해했소 '를 설치' 등을 실행할 수 있습니다.

때문에 훨씬 간단해진다는 apiu 대안이 요청률 비해 많은 장점이 있다. 인증을 해야 할 경우 더욱 그렇다. 이 경우 직관적이지 않은 고통의 루이브 및 urllib2 꽤 있다.

  • 30-12-2015

사람들이 대한 뜻을 진행율 표시줄에는 탄성을 자아냈다. S # 39 멋지다, 그러거라 it&. '지금' 마크 데미 시판용 솔루션 등 여러 가지가 있습니다.

from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

이는 본질적으로 구축상의 @kvance 설명됨 30 개월 전이다.

해설 (12)
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
  output.write(mp3file.read())

open('test.mp3','wb')wb`는 바이너리 모드에서 파일을 열고(기존 파일은 모두 지웁니다) 텍스트 대신 데이터를 저장할 수 있도록 합니다.

해설 (5)

파이썬 3

우를리발리퀘스트 임포트합니다 반응 = http://www.example.com/ 우를리발리퀘스트리어로펜 (& # 39, & # 39;) html = 레스폰지드프리드 ()

우를리발리퀘스트 임포트합니다 http://www.example.com/songs/mp3.mp3 우를리발리퀘스트리우를레리브 (& # 39, & # 39, & # 39, mp3.mp3& # 39;)

파이썬 2

urllib2 임포트합니다 반응 = http://www.example.com/ urllib2.urlopen (& # 39, & # 39;) html = 레스폰지드프리드 ()

루이브 임포트합니다 http://www.example.com/songs/mp3.mp3 우를리발우를레리브 (& # 39, & # 39, & # 39, mp3.mp3& # 39;)

해설 (1)

wget 모듈에서는 사용합니다.

import wget
wget.download('url')
해설 (0)

개선된 버전의 파블로크 파이썬 코드를 2/3.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )

import sys, os, tempfile, logging

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse

def download_file(url, dest=None):
    """ 
    Download and save a file specified by url to dest directory,
    """
    u = urllib2.urlopen(url)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if dest:
        filename = os.path.join(dest, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])
        print("Downloading: {0} Bytes: {1}".format(url, file_size))

        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)

            status = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
            status += chr(13)
            print(status, end="")
        print()

    return filename

if __name__ == "__main__":  # Only run if this file is called directly
    print("Testing with 10MB download")
    url = "http://download.thinkbroadband.com/10MB.zip"
    filename = download_file(url)
    print(filename)
해설 (1)

단순하지만 '파이썬 2 &amp. '6' 3 '에는 호환적 운행에서어떠한 파이썬 라이브러리:

from six.moves import urllib
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
해설 (1)
import os,requests
def download(url):
    get_response = requests.get(url,stream=True)
    file_name  = url.split("/")[-1]
    with open(file_name, 'wb') as f:
        for chunk in get_response.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

download("https://example.com/example.jpg")
해설 (0)

Wget 에서 그냥 순수 파이썬 라이브러리 이 용도로 썼다. 이는 '우를레리브 것가운데 세척하는 것' 을 (를) [이러한 기능을] [2] vmware. 버전 2.0.

[2]: # cl 330 http://support. = 기본 https://bitbucket.org/techtonik/python-wget/src/6859e7b4aba37cef57616111be890fb59631bc4c/wget.py?

해설 (7)

다음은 가장 일반적으로 사용되는 파일 다운로드 요구하고 있다.

1 우를리발우를레리브 (& # 39,, # 39 url_to_file& file_name) '.'

(# 39, & # 39, url_to_file&) '' urllib2.urlopen 2.

리퀘스트s.제 (url) '' 3.

4 우제이다운로이드 (& # 39,, # 39 url& file_name) '.'

참고: '우를로펜 우를레리브 수행할 수 있는' 나쁜 '와' 비교적 대용량 파일 (&gt 크기, 다운로드하십시오 찾을 수 있습니다. 500mb). '저장' 리퀘스트s.제 때까지 인메모리를 파일을 다운로드 완료.

해설 (0)

Corey의 의견에 동의하며, urllib2는 urllib보다 더 완성도가 높으며 더 복잡한 작업을 수행하려는 경우 사용해야 할 모듈이지만, 답변을 더 완벽하게 만들기 위해 기본 사항만 원하는 경우 urllib가 더 간단한 모듈입니다:

import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()

가 잘 작동합니다. 또는 객체를 다루고 싶지 않다면 read()를 직접 호출할 수 있습니다:

import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
해설 (0)

뿐만 아니라 의견을 우를레리브 진행율 구할 수 있습니다.

def report(blocknr, blocksize, size):
    current = blocknr*blocksize
    sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))

def downloadFile(url):
    print "\n",url
    fname = url.split('/')[-1]
    print fname
    urllib.urlretrieve(url, fname, report)
해설 (0)

Wget 설치되어 있는 경우 parallel_sync 사용할 수 있습니다.

pip 설치처 parallel_sync

from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)

Doc: https://pythonhosted.org/parallel_sync/pages/examples.html

이 것은 매우 강력합니다. 이 파일을 다운로드할 수 있으며, 동시에 발생 시 재시도하거나 원격 시스템에서 파일을 다운로드할 수도 있습니다.

해설 (1)

Python3 urllib3 및 슈틸 리브레이어스 에서 사용할 수 있습니다. Pip (여부에 따라 python3 는 기본 방관하겠나) 또는 pip3 사용하여 다운로드하십시오

pip3 install urllib3 shutil

이 코드를 실행하십시오

import urllib.request
import shutil

url = "http://www.somewebsite.com/something.pdf"
output_file = "save_this_name.pdf"
with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

'하지만' 코드 '를 사용할 수 있는' urllib3 루이브 다운로드하십시오 참고

해설 (0)

그냥 생각해서라도 완성도, 또 어떤 프로그램을 사용하여 파일을 검색하는 호출하십시오 하위 '수' 패키지. 프로그램 보다 더 강력한 검색 기능을 'like' 우를레리브 전용임 파일이 있다. 예를 들어, ['wget'] (https://www.gnu.org/software/wget/) 는 디렉터리용 다운로드하십시오 재귀적으로 ('-r'), http, ftp, 리디렉션합니다 통해 해결할 수 프록시를 재 다운로드 피할 수 있는 기존 파일 ('nc') 및 ['aria2'] (https://aria2.github.io/) 다운로드 속도를 높일 수 있는 다중 접속 다운로드 할 수 있습니다.

import subprocess
subprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])

또한 '!' 의 한 프로그램에 직접 협력합니다 호출하십시오 주피터 노트북, 구문.

!wget -O example_output_file.html https://example.com
해설 (0)

만약 속도용 문제에 대한 성능 테스트를 I made to you, '작은' 및 '' 난 '와' wget 루이브 모듈에서는 관한 한 번 없이 한 상태로 표시줄에는 wget 했다. 내가 다른 500MB 파일을 통해 무려 3 테스트하려면 (다른 파일 - 잘 진행되고 있다는 것을 없애기 위해 일부 캐싱과는 후드 아래에). Debian 머시닝할 테스트되었습니다 함께 python2.

첫째, 그것은꿈의 결과 (그들은 비슷한 다른 런입니다):

$ python wget_test.py 
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============

The way I 수행됨 테스트, profile&quot &quot 사용하고 있습니다. 디자이너이다. 이는 전체 코드:

import wget
import urllib
import time
from functools import wraps

def profile(func):
    @wraps(func)
    def inner(*args):
        print func.__name__, ": starting"
        start = time.time()
        ret = func(*args)
        end = time.time()
        print func.__name__, ": {:.2f}".format(end - start)
        return ret
    return inner

url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'

def do_nothing(*args):
    pass

@profile
def urlretrive_test(url):
    return urllib.urlretrieve(url)

@profile
def wget_no_bar_test(url):
    return wget.download(url, out='/tmp/', bar=do_nothing)

@profile
def wget_with_bar_test(url):
    return wget.download(url, out='/tmp/')

urlretrive_test(url1)
print '=============='
time.sleep(1)

wget_no_bar_test(url2)
print '=============='
time.sleep(1)

wget_with_bar_test(url3)
print '=============='
time.sleep(1)

'루이브' 가장 빠른 것 같습니다.

해설 (1)

소스 코드는 다음과 같을 수 있습니다.

import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource  
해설 (0)

피커리 의 파이썬 2 와 3 을 사용할 수 있습니다.

import pycurl

FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'

with open(FILE_DEST, 'wb') as f:
    c = pycurl.Curl()
    c.setopt(c.URL, FILE_SRC)
    c.setopt(c.WRITEDATA, f)
    c.perform()
    c.close()
해설 (0)

난 다음, 바닐라 Python 에서 작동하는 작성했습니까 2gb/s 또는 파이썬 3.

import sys
try:
    import urllib.request
    python3 = True
except ImportError:
    import urllib2
    python3 = False

def progress_callback_simple(downloaded,total):
    sys.stdout.write(
        "\r" +
        (len(str(total))-len(str(downloaded)))*" " + str(downloaded) + "/%d"%total +
        " [%3.2f%%]"%(100.0*float(downloaded)/float(total))
    )
    sys.stdout.flush()

def download(srcurl, dstfilepath, progress_callback=None, block_size=8192):
    def _download_helper(response, out_file, file_size):
        if progress_callback!=None: progress_callback(0,file_size)
        if block_size == None:
            buffer = response.read()
            out_file.write(buffer)

            if progress_callback!=None: progress_callback(file_size,file_size)
        else:
            file_size_dl = 0
            while True:
                buffer = response.read(block_size)
                if not buffer: break

                file_size_dl += len(buffer)
                out_file.write(buffer)

                if progress_callback!=None: progress_callback(file_size_dl,file_size)
    with open(dstfilepath,"wb") as out_file:
        if python3:
            with urllib.request.urlopen(srcurl) as response:
                file_size = int(response.getheader("Content-Length"))
                _download_helper(response,out_file,file_size)
        else:
            response = urllib2.urlopen(srcurl)
            meta = response.info()
            file_size = int(meta.getheaders("Content-Length")[0])
            _download_helper(response,out_file,file_size)

import traceback
try:
    download(
        "https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip",
        "output.zip",
        progress_callback_simple
    )
except:
    traceback.print_exc()
    input()

유라유라테이코쿠:

  • 은 &quot 진행율 bar"; 콜백하는.
  • 다운로드하십시오 4 MB 는 테스트 .zip from my 웹 사이트.
해설 (1)