如何通过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屋!