1001

我有一个小实用程序,用于按计划从网站下载 MP3 文件,然后构建/更新已添加到 iTunes 的播客 XML 文件。

创建/更新 XML 文件的文本处理是用 Python 编写的。但是,我在 Windows 文件中使用 wget.bat来下载实际的 MP3 文件。我更喜欢用 Python 编写整个实用程序。

我很难找到一种在 Python 中实际下载文件的方法,因此我求助于使用wget.

那么,如何使用 Python 下载文件?

4

26 回答 26

1213

还有一个,使用urlretrieve

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

(对于 Python 3+ 使用import urllib.requesturllib.request.urlretrieve

还有一个,带有“进度条”

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()
于 2008-08-22T16:19:09.097 回答
527

使用urllib.request.urlopen()

import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
    html = f.read().decode('utf-8')

这是使用该库的最基本方法,减去任何错误处理。您还可以做更复杂的事情,例如更改标题。

在 Python 2 上,该方法位于urllib2

import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
于 2008-08-22T15:38:22.330 回答
392

2012年,使用python requests 库

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

你可以跑去pip install requests拿。

Requests 与其他替代方案相比具有许多优势,因为 API 更简单。如果您必须进行身份验证,则尤其如此。urllib 和 urllib2 在这种情况下非常不直观和痛苦。


2015-12-30

人们对进度条表示钦佩。这很酷,当然。现在有几种现成的解决方案,包括tqdm

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)

这本质上是 30 个月前描述的 @kvance 实现。

于 2012-05-24T20:08:29.063 回答
165
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
  output.write(mp3file.read())

wbin以open('test.mp3','wb')二进制模式打开一个文件(并删除任何现有文件),因此您可以使用它保存数据而不仅仅是文本。

于 2008-08-22T15:58:17.757 回答
153

蟒蛇 3

  • urllib.request.urlopen

    import urllib.request
    response = urllib.request.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.request.urlretrieve

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

    注意:根据文档,urllib.request.urlretrieve是“遗留接口”并且“将来可能会被弃用”(感谢gerrit

蟒蛇2

于 2015-08-06T13:30:31.577 回答
44

使用wget 模块

import wget
wget.download('url')
于 2015-03-25T12:59:25.247 回答
36
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")
于 2018-11-05T11:28:18.010 回答
24

Python 2/3 的 PabloG 代码的改进版本:

#!/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)
于 2013-05-13T08:59:44.083 回答
22

简单但Python 2 & Python 3兼容的方式带有six库:

from six.moves import urllib
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
于 2017-06-22T07:59:35.557 回答
20

以下是在 python 中下载文件最常用的调用:

  1. urllib.urlretrieve ('url_to_file', file_name)

  2. urllib2.urlopen('url_to_file')

  3. requests.get(url)

  4. wget.download('url', file_name)

注意:下载大文件(大小 > 500 MB)时性能相对较差urlopen。将文件存储在内存中,直到下载完成。 urlretrieverequests.get

于 2016-09-19T12:45:10.550 回答
19

为此目的,用纯 Python编写了wget库。从 2.0 版开始,它就urlretrieve具备了这些功能

于 2013-09-25T17:55:16.610 回答
16

在 python3 中,您可以使用 urllib3 和 shutil libraires。使用 pip 或 pip3 下载它们(取决于 python3 是否为默认值)

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)

请注意,您下载urllib3urllib在代码中使用

于 2018-02-08T17:30:45.830 回答
15

我同意 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()
于 2008-08-22T15:58:52.077 回答
10

如果你安装了 wget,你可以使用 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)

文档: https ://pythonhosted.org/parallel_sync/pages/examples.html

这是相当强大的。它可以并行下载文件,失败重试,甚至可以在远程机器上下载文件。

于 2015-11-19T23:48:06.740 回答
9

您也可以使用 urlretrieve 获得进度反馈:

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)
于 2014-01-26T13:12:54.657 回答
5

如果速度对你很重要,我对模块urllib和进行了一个小的性能测试wget,关于wget我尝试了一次使用状态栏和一次没有。我拿了三个不同的 500MB 文件进行测试(不同的文件 - 以消除在后台进行缓存的可能性)。在 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
==============

我执行测试的方式是使用“profile”装饰器。这是完整的代码:

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)

urllib似乎是最快的

于 2017-11-03T14:25:38.253 回答
5

只是为了完整起见,也可以调用任何程序来使用subprocess包检索文件。专门用于检索文件的程序比 Python 函数(如urlretrieve. 例如,可以递归wget下载目录-R-ncaria2

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

在 Jupyter Notebook 中,也可以直接调用程序,!语法如下:

!wget -O example_output_file.html https://example.com
于 2018-08-29T12:24:49.620 回答
5

迟到的答案,但python>=3.6你可以使用:

import dload
dload.save(url)

安装dload

pip3 install dload
于 2020-02-24T07:12:14.373 回答
4

源代码可以是:

import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource  
于 2013-11-26T13:21:01.657 回答
4

我写了以下内容,它适用于普通 Python 2 或 Python 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()

笔记:

  • 支持“进度条”回调。
  • 从我的网站下载一个 4 MB 的测试 .zip。
于 2017-05-13T21:33:30.713 回答
4

您可以在 Python 2 和 3 上使用PycURL 。

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()
于 2018-08-08T03:51:42.353 回答
3

这可能有点晚了,但是我看到了 pabloG 的代码,忍不住添加了一个 os.system('cls') 让它看起来很棒!看看这个 :

    import urllib2,os

    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)
    os.system('cls')
    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()

如果在 Windows 以外的环境中运行,则必须使用“cls”以外的其他内容。在 MAC OS X 和 Linux 中,它应该是“清晰的”。

于 2013-10-14T02:54:01.890 回答
3

urlretrieve 和 requests.get 很简单,但事实并非如此。我已经为几个站点获取了数据,包括文本和图像,以上两个可能解决了大部分任务。但对于更通用的解决方案,我建议使用 urlopen。由于它包含在 Python 3 标准库中,因此您的代码可以在任何运行 Python 3 的机器上运行,而无需预先安装站点包

import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)

#remember to open file in bytes mode
with open(filename, 'wb') as f:
    while True:
        buffer = url_connect.read(buffer_size)
        if not buffer: break

        #an integer value of size of written data
        data_wrote = f.write(buffer)

#you could probably use with-open-as manner
url_connect.close()

当使用 Python 通过 http 下载文件时,此答案提供了 HTTP 403 Forbidden 的解决方案。我只尝试了 requests 和 urllib 模块,其他模块可能会提供更好的东西,但这是我用来解决大部分问题的模块。

于 2017-03-13T13:12:19.473 回答
3

新的基于 Api urllib3 的实现

>>> import urllib3
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', 'your_url_goes_here')
>>> r.status
   200
>>> r.data
   *****Response Data****

更多信息:https ://pypi.org/project/urllib3/

于 2021-07-02T12:00:24.693 回答
0

我想从网页下载所有文件。我试过wget了,但失败了,所以我决定使用 Python 路线,我找到了这个线程。

阅读后,我做了一个小命令行应用程序,扩展了PabloGStansoupget的优秀答案,并添加了一些有用的选项。

它使用BeatifulSoup收集页面的所有 URL,然后下载具有所需扩展名的 URL。最后它可以并行下载多个文件。

这里是:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function, unicode_literals)
import sys, os, argparse
from bs4 import BeautifulSoup

# --- insert Stan's script here ---
# if sys.version_info >= (3,): 
#...
#...
# def download_file(url, dest=None): 
#...
#...

# --- new stuff ---
def collect_all_url(page_url, extensions):
    """
    Recovers all links in page_url checking for all the desired extensions
    """
    conn = urllib2.urlopen(page_url)
    html = conn.read()
    soup = BeautifulSoup(html, 'lxml')
    links = soup.find_all('a')

    results = []    
    for tag in links:
        link = tag.get('href', None)
        if link is not None: 
            for e in extensions:
                if e in link:
                    # Fallback for badly defined links
                    # checks for missing scheme or netloc
                    if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):
                        results.append(link)
                    else:
                        new_url=urlparse.urljoin(page_url,link)                        
                        results.append(new_url)
    return results

if __name__ == "__main__":  # Only run if this file is called directly
    # Command line arguments
    parser = argparse.ArgumentParser(
        description='Download all files from a webpage.')
    parser.add_argument(
        '-u', '--url', 
        help='Page url to request')
    parser.add_argument(
        '-e', '--ext', 
        nargs='+',
        help='Extension(s) to find')    
    parser.add_argument(
        '-d', '--dest', 
        default=None,
        help='Destination where to save the files')
    parser.add_argument(
        '-p', '--par', 
        action='store_true', default=False, 
        help="Turns on parallel download")
    args = parser.parse_args()

    # Recover files to download
    all_links = collect_all_url(args.url, args.ext)

    # Download
    if not args.par:
        for l in all_links:
            try:
                filename = download_file(l, args.dest)
                print(l)
            except Exception as e:
                print("Error while downloading: {}".format(e))
    else:
        from multiprocessing.pool import ThreadPool
        results = ThreadPool(10).imap_unordered(
            lambda x: download_file(x, args.dest), all_links)
        for p in results:
            print(p)

其用法示例如下:

python3 soupget.py -p -e <list of extensions> -d <destination_folder> -u <target_webpage>

如果你想看到它的实际效果,还有一个实际的例子:

python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics
于 2020-03-06T00:17:19.937 回答
-2

另一种方法是调用外部进程,例如 curl.exe。Curl 默认显示进度条、平均下载速度、剩余时间等,所有这些都整齐地排列在表格中。将 curl.exe 与脚本放在同一目录中

from subprocess import call
url = ""
call(["curl", {url}, '--output', "song.mp3"])

注意:您不能使用 curl 指定输出路径,因此请在之后执行 os.rename

于 2020-09-14T00:20:55.737 回答