如何使用我已经知道其URL地址的Python在本地保存图像?

2024-04-23 17:12:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道互联网上图片的网址。

例如http://www.digimouth.com/news/media/2011/09/google-logo.jpg,其中包含Google的徽标。

现在,如何使用Python下载此图像,而不必在浏览器中实际打开URL并手动保存文件。


Tags: 图像comhttpwwwgoogle图片互联网media
3条回答

Python2

如果您只想将其另存为文件,下面是一个更简单的方法:

import urllib

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

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

Python3

正如SergO所建议的,下面的代码应该与Python 3一起工作。

import urllib.request

urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
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将包含您的图像。

我写了a script that does just this,它可以在我的github上供您使用。

我利用美化组让我可以解析任何网站的图像。如果你要做大量的网页抓取(或打算使用我的工具),我建议你sudo pip install BeautifulSoup。有关美化组的信息可从here获得。

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

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

相关问题 更多 >