2015-07-19 95 views
-1

我现在正在编写一个从互联网抓取图像并使用它们启动服务器并写入html的程序。如何将图像放到本地主机服务器上

这里是我的代码:

import json 
import requests 
import urllib2 
import webserver 
import bottle 
from bottle import run, route, request 

#get images 
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json") 
r.text 
imageli = json.loads(r.text) 
i = 1 
for image in imageli: 
    if i <= 5: 
     fname = str(i)+".png" 
     urllib.urlretrieve(image,fname) 
     i += 1 

#to start a server 
@route('/') 
#write a HTML, here is where the problem is, 
#the content of html is <image src= "1.png"> but the picture is not on the server. 
#and I don't know how to do it 
def index(): 
    return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>" 
if __name__ == '__main__':   
    bottle.debug(True) 
    run(host='localhost', port=8080, reloader=True) 

,我有该图像不能在网站上显示的问题,控制台说,图像不能被发现。

我该如何解决这个问题?

+0

该问题是下载或服务的一部分?请首先将您遇到的问题的代码减少到最小的示例。另见http://sscce.org。 –

+0

你已经在本地保存了图像,并且有一条瓶子路线,它提供了一些链接到它们的HTML,但是实际上为图像提供服务的代码在哪里? –

+0

问题是,在服务器上,图像不能上传,因为它保存在本地。而我刚刚上传我的代码 –

回答

0

这里的问题是您尚未定义用于提供静态文件的路径。您可以设置根目录中加入这条航线为静态文件:

# To serve static png files from root. 
@bottle.get('/<filename:re:.*\.png>') 
def images(filename): 
    return bottle.static_file(filename, root='') 

但你真的应该将这些到一个子目录,如:

import json 
import requests 
import urllib 
import bottle 
from bottle import run, route, request 

#get images 
r = requests.get("http://web.sfc.keio.ac.jp/~t14527jz/midterm/imagelist.json") 
r.text 
imageli = json.loads(r.text) 
i = 1 
for image in imageli: 
    if i <= 5: 
     fname = "static/{}.png".format(i) # Note update here 
     urllib.urlretrieve(image, fname) 
     i += 1 

#to start a server 
@route('/') 
def index(): 
    return "<html><head><title>Final exam</title></head><body> <img src=\"1.png\"/>\n <img src=\"2.png\"/>\n <img src=\"3.png\"/>\n<img src=\"4.png\"/>\n<img src=\"5.png\"/>\n</body></html>" 

# To serve static image files from static directory 
@bottle.get('/<filename:re:.*\.(jpg|png|gif|ico)>') 
def images(filename): 
    return bottle.static_file(filename, root='static') 

if __name__ == '__main__': 
    bottle.debug(True) 
    run(host='localhost', port=8080, reloader=True) 
相关问题