开发者

Python -- how to grab images off the internet

开发者 https://www.devze.com 2023-03-14 00:33 出处:网络
How can I grab a picture off of a known url and save it to my computer using Python开发者_开发知识库 (v2.6)? ThanksYou can use urllib.urlretrieve.

How can I grab a picture off of a known url and save it to my computer using Python开发者_开发知识库 (v2.6)? Thanks


You can use urllib.urlretrieve.

Copy a network object denoted by a URL to a local file, if necessary.

Example:

>>> import urllib
>>> urllib.urlretrieve('http://i.imgur.com/Ph4Xw.jpg', 'duck.jpg')
('duck.jpg', <httplib.HTTPMessage instance at 0x10118e830>)
# by now the file should be downloaded to 'duck.jpg'


You can use urllib.urlretrieve:

import urllib
urllib.urlretrieve('http://example.com/file.png', './file.png')

If you need more flexibility, use urllib2.


In the absence of any context, the following is a simple example of using standard library modules to make an non-authenticated HTTP GET request

import urllib2
response = urllib2.urlopen('http://lolcat.com/images/lolcats/1674.jpg')
with open('lolcat.jpg', 'wb') as outfile:
    outfile.write(response.read())

EDIT: urlretrieve() is new to me. I guess then you could turn it into a command line one-liner... if you're bored.

$ python -c "import urllib; urllib.urlretrieve('http://lolcat.com/images/lolcats/1674.jpg', filename='/tmp/1674.jpg')"


batteries are included in urllib:

urllib.urlretrieve(yourUrl, fileName)


import urllib2
open("fish.jpg", "w").write(urllib2.urlopen("http://www.fiskeri.no/Fiskeslag/Fjesing.jpg").read())


Easy.

import urllib
urllib.urlretrieve("http://www.dokuwiki.org/_media/wiki:dokuwiki-128.png","dafile.png")
0

精彩评论

暂无评论...
验证码 换一张
取 消