Python:从网页保存图片到磁盘

4 投票
3 回答
4028 浏览
提问于 2025-04-16 02:19

我可以用Python把图片保存到电脑上吗?下面是一个图片的例子:

在这里输入图片描述

3 个回答

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

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

撰写回答