基本的http文件在python中下载并保存到磁盘?
Posted
技术标签:
【中文标题】基本的http文件在python中下载并保存到磁盘?【英文标题】:Basic http file downloading and saving to disk in python? 【发布时间】:2013-10-26 04:49:27 【问题描述】:我是 Python 新手,我一直在浏览这个网站上的问答,以回答我的问题。但是,我是初学者,我发现很难理解一些解决方案。我需要一个非常基本的解决方案。
有人可以向我解释一下“通过 http 下载文件”和“在 Windows 中将文件保存到磁盘”的简单解决方案吗?
我也不确定如何使用 shutil 和 os 模块。
我要下载的文件小于 500 MB,是一个 .gz 存档文件。如果有人能解释如何提取存档并利用其中的文件,那就太好了!
这是一个部分解决方案,是我结合各种答案写的:
import requests
import os
import shutil
global dump
def download_file():
global dump
url = "http://randomsite.com/file.gz"
file = requests.get(url, stream=True)
dump = file.raw
def save_file():
global dump
location = os.path.abspath("D:\folder\file.gz")
with open("file.gz", 'wb') as location:
shutil.copyfileobj(dump, location)
del dump
有人能指出错误(初级)并解释更简单的方法吗?
谢谢!
【问题讨论】:
注意如果你是从pycharm下载的注意谁知道“当前文件夹在哪里” 【参考方案1】:下载文件的简洁方法是:
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
这将从网站下载文件并将其命名为file.gz
。这是我最喜欢的解决方案之一,来自Downloading a picture via urllib and python。
本例使用urllib
库,它会直接从源中检索文件。
【讨论】:
好的,谢谢!但是有没有办法让它通过请求工作? 是否有可能保存在 /myfolder/file.gz 中? 没有比自己尝试更好的可能吧? :) 我可以成功地做到testfile.retrieve("http://example.com/example.rpm", "/tmp/test.rpm")
。
自 Python 3.3 起已弃用,而 urllib.request.urlretrieve 解决方案(见下面的答案)是“现代”方式
在此代码中添加用户名和密码的最佳方法是什么? tks【参考方案2】:
如上所述here:
import urllib
urllib.urlretrieve ("http://randomsite.com/file.gz", "file.gz")
EDIT:
如果你还想用requests,看看this question或者this one。
【讨论】:
urllib 会起作用,但是,许多人似乎建议使用请求而不是 urllib。为什么会这样?requests
与 urllib
相比在使用 REST API 时非常有用。除非,你想做更多,这应该是好的。
好的,现在我已经阅读了您为请求使用提供的链接。我对如何声明文件路径以保存下载感到困惑。我该如何使用 os 和 shutil?
对于 Python3:import urllib.request
urllib.request.urlretrieve(url, filename)
如果下载失败,我将无法提取 http 状态码【参考方案3】:
对于 Python3+,URLopener
已弃用。
使用时会报如下错误:
url_opener = urllib.URLopener() AttributeError: module 'urllib' has no 属性“URLopener”
那么,试试吧:
import urllib.request
urllib.request.urlretrieve(url, filename)
【讨论】:
奇怪...为什么当 Python 2 被弃用并且只有这个解决方案才能正常工作时没有人投票支持这个答案... 同意!我在早期的解决方案中拉扯我的头发。希望我能投票 200 次! 如何指明保存url内容的文件夹/路径? 注意如果你是从pycharm下载的,注意谁知道“当前文件夹在哪里”【参考方案4】:使用 wget、urllib 和 request 的四种方法。
#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile as profile
import urllib
import wget
url = 'https://tinypng.com/images/social/website.jpg'
def testRequest():
image_name = 'test1.jpg'
r = requests.get(url, stream=True)
with open(image_name, 'wb') as f:
for chunk in r.iter_content():
f.write(chunk)
def testRequest2():
image_name = 'test2.jpg'
r = requests.get(url)
i = Image.open(StringIO(r.content))
i.save(image_name)
def testUrllib():
image_name = 'test3.jpg'
testfile = urllib.URLopener()
testfile.retrieve(url, image_name)
def testwget():
image_name = 'test4.jpg'
wget.download(url, image_name)
if __name__ == '__main__':
profile.run('testRequest()')
profile.run('testRequest2()')
profile.run('testUrllib()')
profile.run('testwget()')
testRequest - 在 20.236 秒内完成 4469882 次函数调用(4469842 次原始调用)
testRequest2 - 8580 个函数调用(8574 个原始调用)在 0.072 秒内
testUrllib - 3810 次函数调用(3775 次原始调用)在 0.036 秒内
testwget - 3489 次函数调用在 0.020 秒内
【讨论】:
你是怎么得到函数调用次数的?【参考方案5】:我使用wget。
如果你想举个例子,简单又好用的库?
import wget
file_url = 'http://johndoe.com/download.zip'
file_name = wget.download(file_url)
wget 模块支持 python 2 和 python 3 版本
【讨论】:
【参考方案6】:异域 Windows 解决方案
import subprocess
subprocess.run("powershell Invoke-WebRequest -OutFile ".format(your_url, filename), shell=True)
【讨论】:
【参考方案7】:import urllib.request
urllib.request.urlretrieve("https://raw.githubusercontent.com/dnishimoto/python-deep-learning/master/list%20iterators%20and%20generators.ipynb", "test.ipynb")
将单个原始 juypter notebook 下载到文件中。
【讨论】:
【参考方案8】:我开始走这条路是因为 ESXi 的 wget 没有使用 SSL 编译,我想从供应商的网站直接下载 OVA 到世界另一端的 ESXi 主机上。
我必须通过编辑规则(正确)禁用防火墙(惰性)/启用 https
创建了 python 脚本:
import ssl
import shutil
import tempfile
import urllib.request
context = ssl._create_unverified_context()
dlurl='https://somesite/path/whatever'
with urllib.request.urlopen(durl, context=context) as response:
with open("file.ova", 'wb') as tmp_file:
shutil.copyfileobj(response, tmp_file)
ESXi 库有点成对了,但开源 weasel 安装程序似乎使用 urllib 进行 https...所以它启发了我走这条路
【讨论】:
【参考方案9】:对于文本文件,您可以使用:
import requests
url = 'https://WEBSITE.com'
req = requests.get(url)
path = "C:\\YOUR\\FILE.html"
with open(path, 'wb') as f:
f.write(req.content)
【讨论】:
你不需要req.iter_content()
吗?还是使用req.raw
文件对象?见this
不,它只是工作,你没试过吗? @MichaelSchnerring【参考方案10】:
另一种保存文件的干净方法是:
import csv
import urllib
urllib.retrieve("your url goes here" , "output.csv")
【讨论】:
这应该是urllib.urlretrieve
或urllib.URLopener().retrieve
,不清楚你的意思。
如果只是命名文件,为什么还要导入 csv?以上是关于基本的http文件在python中下载并保存到磁盘?的主要内容,如果未能解决你的问题,请参考以下文章
自动点击下载链接后,使用 Selenium、Firefox、Python 将下载的 EPS 文件保存到磁盘