如何用Python将已知网址的图片保存到本地?

206 投票
18 回答
350285 浏览
提问于 2025-04-17 07:09

我知道一个在网上的图片链接。

比如说这个链接:http://www.digimouth.com/news/media/2011/09/google-logo.jpg,它是谷歌的标志。

现在,我想知道怎么用Python下载这张图片,而不需要在浏览器里打开这个链接,然后手动保存文件。

18 个回答

21

我写了一个脚本,专门用来做这个事情,你可以在我的GitHub上找到它,随便使用。

我用了一个叫BeautifulSoup的工具,这样我就可以从任何网站上提取图片。如果你打算经常进行网页抓取(或者想用我的工具),我建议你运行 sudo pip install BeautifulSoup 来安装它。关于BeautifulSoup的更多信息可以在这里找到。

为了方便起见,这里是我的代码:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import urllib

# use this image scraper from the location that 
#you want to save scraped images to

def make_soup(url):
    html = urlopen(url).read()
    return BeautifulSoup(html)

def get_images(url):
    soup = make_soup(url)
    #this makes a list of bs4 element tags
    images = [img for img in soup.findAll('img')]
    print (str(len(images)) + "images found.")
    print 'Downloading images to current working directory.'
    #compile our unicode list of image links
    image_links = [each.get('src') for each in images]
    for each in image_links:
        filename=each.split('/')[-1]
        urllib.urlretrieve(each, filename)
    return image_links

#a standard call looks like this
#get_images('http://www.wookmark.com')
29
import urllib
resource = urllib.urlopen("http://www.digimouth.com/news/media/2011/09/google-logo.jpg")
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()

file01.jpg 这个文件里会放你的图片。

407

Python 2

如果你只是想把它保存为一个文件,这里有个更简单的方法:

import urllib

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

第二个参数是你想把文件保存到的本地路径。

Python 3

正如SergO所建议的,下面的代码应该可以在Python 3中运行。

import urllib.request

urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

撰写回答