简体   繁体   English

如何使用Python下载文件

[英]How to download a file using Python

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. 我尝试使用Python从Internet下载某些内容,但我使用的是urllib模块中的urllib.retriever ,但我无法使其正常运行。 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. 如果有人可以用清晰的例子向我解释如何做到这一点,将不胜感激。

I suggest using urllib2 like so: 我建议像这样使用urllib2

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

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 ): 你甚至可以缩短到(虽然,你不会想缩短,如果你打算包围在每个单独的呼叫try - except ):

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

You can also use the urllib: 您还可以使用urllib:

source = urllib.request.urlopen(("full_url")).read()

and then use what chown used above: 然后使用上面使用的chown:

open("/path/to/someFile", "wb").write(source)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM