如何使用 Python 下载文件 [英] How to download a file using Python

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

问题描述

我尝试使用 Python 从 Internet 下载某些内容,我正在使用 urllib 模块中的 urllib.retriever 但我无法让它工作.我希望能够将下载的文件保存到我选择的位置.如果有人能用清晰的例子向我解释如何做到这一点,我将不胜感激.

I tried to download something from the Internet using Python, I am using urllib.retriever from the urllib module but I just can't get it work. I would like to be able to save the downloaded file to a location of my choice. If someone could explain to me how to do it with clear examples, that would be VERY appreciated.

推荐答案

我建议使用 urllib2 像这样:

I suggest using urllib2 like so:

source = urllib2.urlopen("http://someUrl.com/somePage.html").read()
open("/path/to/someFile", "wb").write(source)

您甚至可以将其缩短为(尽管,如果您计划将每个单独的调用包含在 try - except 中,您不会想要缩短它):

You could even shorten it to (although, you wouldnt want to shorten it if you plan to enclose each individual call in a try - except):

open("/path/to/someFile", "wb").write(urllib2.urlopen("http://someUrl.com/somePage.html").read())

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

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