我知道互联网上一张图片的网址。
例如,http://www.digimouth.com/news/media/2011/09/google-logo.jpg,其中包含谷歌的徽标。
现在,我如何使用Python下载此图像,而无需在浏览器中实际打开URL并手动保存文件。
发布于 2011-11-27 23:01:14
Python 2
如果您只想将其另存为文件,这里有一种更简单的方法:
import urllib
urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
第二个参数是保存文件的本地路径。
Python 3
正如SergO建议的那样,下面的代码应该可以与Python3一起使用。
import urllib.request
urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
发布于 2011-11-27 22:51:16
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
将包含您的图像。
发布于 2014-04-19 01:36:59
我写了a script that does just this,你可以在我的github上使用它。
我利用BeautifulSoup来解析任何网站的图片。如果你要做大量的网页抓取(或者打算使用我的工具),我建议你使用sudo pip install BeautifulSoup
。有关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')
https://stackoverflow.com/questions/8286352
复制相似问题