如何通过 HTTP 下载文件? [英] How to download a file over HTTP?
问题描述
我有一个小实用程序,用于按计划从网站下载 MP3 文件,然后构建/更新已添加到 iTunes 的播客 XML 文件.
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
创建/更新 XML 文件的文本处理是用 Python 编写的.但是,我在 Windows .bat
文件中使用 wget 来下载实际的 MP3 文件.我更喜欢用 Python 编写整个实用程序.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat
file to download the actual MP3 file. I would prefer to have the entire utility written in Python.
我一直在努力寻找一种在 Python 中实际下载文件的方法,因此我求助于使用 wget
.
I struggled to find a way to actually download the file in Python, thus why I resorted to using wget
.
那么,如何使用 Python 下载文件?
So, how do I download the file using Python?
推荐答案
import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
html = f.read().decode('utf-8')
这是使用库的最基本方式,减去任何错误处理.您还可以执行更复杂的操作,例如更改标题.
This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers.
在 Python 2 上,该方法位于 urllib2
一个>:
On Python 2, the method is in urllib2
:
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
这篇关于如何通过 HTTP 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!