python下载文件的三种要领
Python开拓中时长碰着要下载文件的环境,最常用的要领就是通过Http操作urllib可能urllib2模块。
虽然你也可以操作ftplib从ftp站点下载文件。另外Python还提供了别的一种要领requests。
下面来看看三种要领是如何来下载zip文件的:
要领一:
import urllib import urllib2 import requests print "downloading with urllib" url = 'http://www.pythontab.com/test/demo.zip' print "downloading with urllib" urllib.urlretrieve(url, "demo.zip")
要领二:
import urllib2 print "downloading with urllib2" url = 'http://www.pythontab.com/test/demo.zip' f = urllib2.urlopen(url) data = f.read() with open("demo2.zip", "wb") as code: code.write(data)
要领三:
import requests print "downloading with requests" url = 'http://www.pythontab.com/test/demo.zip' r = requests.get(url) with open("demo3.zip", "wb") as code: code.write(r.content)
看起来利用urllib最为简朴,一句语句即可。虽然你可以把urllib2缩写成:
f = urllib2.urlopen(url)
with open("demo2.zip", "wb") as code:
code.write(f.read())