Python:将图像从web保存到磁盘

Python:将图像从web保存到磁盘,python,Python,我可以使用python将图像保存到磁盘吗?图像的一个示例是: 谷歌图表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

我可以使用python将图像保存到磁盘吗?图像的一个示例是:


谷歌图表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肯定会对您有所启发。

最简单的方法是使用

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')

如果您的目标是将png下载到磁盘,您可以通过以下方式完成:

在Python3中,需要使用
urllib.request.urlretrieve
而不是
urllib.urlretrieve

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)