2015-07-12 72 views
-1

联系我:如何HTML文件中的蟒蛇

fruits = [apple, banana, pineapple, oranges] 
sizes = [small, medium, large] 

我创建具有每个水果和大小组合fruitproperties HTML页面。

基本上我的Python脚本名称创建文件夹:

apple, banana, pineapple, oranges 

每个果实文件夹中有三个子文件夹名称为:

small, medium, large 

每个文件夹中包含一个HTML文件各自的大小名称。像

small has small.html 
medium has medium.html 
large has large.html 

,它包含了fruitproperties特定fruit-size combination

因此,所有的html页面有如下类似的路径:

script-path/fruit/size/size.html 

现在我想所有这些网页链接到我的HTML索引页。但我是新来的蟒蛇,不知道如何利用路径(我可以使用Python中的href创建os.path.join)路径

以下是我的代码:

def html_home(fruit,size): 
    htmlFile = open(fruit+".html","w") 
    htmlFile.write("!DOCTYPE html>\n") 
    htmlFile.write("<html>\n") 
    htmlFile.write("<title> Fruitproperites </title>\n") 
    htmlFile.write("<head>") 
    htmlFile.write("<body>") 
    htmlFile.write("<h1> List of fruitproperties </h1>\n") 
    # By the time, I call html_home() function, there is already  
    # respective size.html page been created in each fruit/size folder. 
    # all have path as: scriptpath/fruit/size/size.html 
    scriptpath = os.path.dirname(os.path.abspath(__file__)) 
    htmlpath = os.path.join(scriptpath,target,size,size+".html") 
    htmlFile.write('<a href = htmlpath> +size+ '</a>'<br><\n>') 
    htmlFile.write("</body>\n") 
    htmlFile.write("</html>\n") 
    htmlFile.close() 

    # Following code works fine 
    htmlFile = open('home.html','w') 
    htmlFile.write("<!DOCTYPE html> \n") 
    htmlFile.write("<html>\n") 
    htmlFile.write("<head>\n") 
    htmlFile.write("<title> Fruitproperties</title>\n") 
    htmlFile.write("<body>\n") 
    for fruit in fruits: 
     htmlFile.write('<a href="'+fruit+'.html"> List of functions -'+target+'</a><br>\n') 
    htmlFile.write("<body>\n") 
    htmlFile.write("</html?\n") 
    htmlFile.close() 

有谁能够与链接帮助在代码上半年size.html 的?我是新来的蟒蛇。可能是由于错位的引号

回答

1

你的问题

htmlFile.write('<a href = htmlpath> +size+ '</a>'<br><\n>') 

它也会创建错误的HTML。

你应该使用其他的方法来编写HTML,一个简单的如果使用模板字符串。在Python字符串可以去多行,然后创建一个上下文字典,并使用它的格式字符串:

templ = '''<!DOCTYPE html> 
<html> 
<title> Fruitproperites </title> 
<head> 
<body> 
<h1> List of fruitproperties </h1> 
<a href="%(href)s">%(size)s</a><br> 
</body> 
</html>''' 
context = {} 
context['href'] = 'http://yoursite.tld/' 
context['size'] = size 
html = templ % context 

然后马上为你已经做了写html内容!

要链接到本地​​文件而不是http资源,请使用file: URI架构。获得这种链接最简单的方法是在浏览器中打开文件并检查URL栏。