2010-08-04 54 views

回答

3

最简单的就是使用urllib.urlretrieve

的Python 2:

import urllib 
urllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png') 

的Python 3:

import urllib.request 
urllib.request.urlretrieve('http://chart.apis.google.com/...', 'outfile.png') 
0

的谷歌图表API产生PNG文件。只需用urllib.urlopen(url).read()或其他方式检索它们,并按照常规方式安全地保存到文件中。

完整的示例:

>>> import urllib 
>>> url = 'http://chart.apis.google.com/chart?chxl=1:|0|10|100|1%2C000|10%2C000|100%2C000|1%2C000%2C000|2:||Excretion+in+Nanograms+per+gram+creatinine+milliliter+(logarithmic+scale)|&chxp=1,0|2,0&chxr=0,0,12.1|1,0,3&chxs=0,676767,13.5,0,lt,676767|1,676767,13.5,0,l,676767&chxtc=0,-1000&chxt=y,x,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,12.1&chd=t:0,0,0,0,0,0,0,0,0,1,0,0,3,2,4,6,6,9,3,6,5,11,9,10,6,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&chdl=n=87&chtt=William+MD+-+Buprenorphine+Graph' 
>>> image = urllib.urlopen(url).read() 
>>> outfile = open('chart01.png','wb') 
>>> outfile.write(image) 
>>> outfile.close() 

正如在其他的例子指出,“urllib.urlretrieve(URL,outfilename)`是更简单,但urllib而玩的urllib2一定会启发你。

1

如果你的目标是要下载一个PNG到磁盘,您可以用urllib这样做:

import urllib 
urladdy = "http://chart.apis.google.com/chart?chxl=1:|0|10|100|1%2C000|10%2C000|100%2C000|1%2C000%2C000|2:||Excretion+in+Nanograms+per+gram+creatinine+milliliter+(logarithmic+scale)|&chxp=1,0|2,0&chxr=0,0,12.1|1,0,3&chxs=0,676767,13.5,0,lt,676767|1,676767,13.5,0,l,676767&chxtc=0,-1000&chxt=y,x,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,12.1&chd=t:0,0,0,0,0,0,0,0,0,1,0,0,3,2,4,6,6,9,3,6,5,11,9,10,6,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&chdl=n=87&chtt=William+MD+-+Buprenorphine+Graph" 
filename = r"c:\tmp\toto\file.png" 
urllib.urlretrieve(urladdy, filename) 

在python 3,你将需要使用urllib.request.urlretrieve而不是urllib.urlretrieve