Skip to main content
 首页 » 编程设计

python之如何使用 Python 下载文件

2025年05月04日11wuhuacong

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

请您参考如下方法:

我建议使用 urllib2像这样:

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

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

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