Python下载文件 [英] Python download a file
问题描述
我不确定该怎么做.一种方法是:
I'm unsure how to do this. One way is:
import urllib.request;
urllib.request.urlretrieve('www.example.com/file.tar', 'file.tar')
另一种方式是:
import urllib.request;
#Set as appropriate
userAgent = ....;
req = urllib.request.Request('www.example.com/file.tar', headers={'User-Agent' : userAgent});
response = urllib.request.urlopen(req);
#Save the file
f = open('file.tar', 'wb');
f.write(response.read());
f.close()
我不确定要使用哪种方法.我将循环下载许多文件(带有模式文件名).但是,我希望能够设置一个用户代理标头.这并不重要,但我想这么做.
I'm not sure which method to use. I'll be downloading many files (with a pattern filename) in a loop. However, I would like to be able to set up a user-agent header. It's not critical but I'd like to.
我忘了提到我更喜欢第一种方法,但是我不知道如何使用urlretrieve设置用户代理标头.
I forgot to mention that I prefer the first method but I don't know how to set the user-agent header with urlretrieve.
推荐答案
我正在将以注释开头的内容移至答案...
I am moving what started as comments, to an answer...
您的第二个示例几乎完成了所需的工作,即创建带有自定义标头的请求对象,然后将结果读取到本地文件中.
Your second example is pretty much doing what it needs to, in making a request object with a custom header and then reading the results into a local file.
urlretrieve
是更高级别的功能,因此它仅能按照文档所说的进行操作:将网络资源下载到本地文件中,并告诉您该文件在何处.如果您不喜欢第二个示例中的较低级别方法,并且想要更多高级功能,则可以使用
urlretrieve
is a higher level function so it only does exactly what the docs say: Downloads a network resource to a local file and tells you where the file is. If you don't like the slightly lower level approach of your second example and you want more higher-level functionality, you can look into using the Requests library
这篇关于Python下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!