如何使用Python通过HTTP下载文件? [英] How do I download a file over HTTP using Python?

查看:144
本文介绍了如何使用Python通过HTTP下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.

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

The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows .bat file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.

我很难找到一种方法来实际下载Python中的文件,因此我采用了 wget

I struggled though to find a way to actually down load the file in Python, thus why I resorted to wget.

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

So, how do I download the file using Python?

推荐答案

在Python 2中,使用标准库附带的urllib2。

In Python 2, use urllib2 which comes with the standard library.

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

这是使用库的最基本方法,减去任何错误处理。您还可以执行更复杂的操作,例如更改标题。可以在此处找到该文档。

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. The documentation can be found here.

这篇关于如何使用Python通过HTTP下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆