2015-07-12 46 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欄。