首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用我已经知道URL地址的Python在本地保存图像?

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

Stack Overflow用户
提问于 2011-11-27 22:46:38
回答 16查看 293.9K关注 0票数 183

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

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

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

EN

回答 16

Stack Overflow用户

回答已采纳

发布于 2011-11-27 23:01:14

Python 2

如果您只想将其另存为文件,这里有一种更简单的方法:

代码语言:javascript
复制
import urllib

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

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

Python 3

正如SergO建议的那样,下面的代码应该可以与Python3一起使用。

代码语言:javascript
复制
import urllib.request

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

Stack Overflow用户

发布于 2011-11-27 22:51:16

代码语言:javascript
复制
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将包含您的图像。

票数 28
EN

Stack Overflow用户

发布于 2014-04-19 01:36:59

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

我利用BeautifulSoup来解析任何网站的图片。如果你要做大量的网页抓取(或者打算使用我的工具),我建议你使用sudo pip install BeautifulSoup。有关BeautifulSoup的信息,请访问here

为了方便起见,下面是我的代码:

代码语言:javascript
复制
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')
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8286352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档