2017-02-19 70 views
0

我一直在試圖弄清楚這幾天,我有點疲憊,即使是最有效的谷歌搜索。我一直在試圖打開一個類型爲HTML的文件,並使用Go的庫(http://golang.org/x/net/html)將img標籤及其源代碼修改爲已知目錄和文件集。到目前爲止,我已經能夠找到使用這個元素,如何使用Go修改HTML文件的元素?

//Open the file and return a variable called file. 
file, _ = os.Open(file.Name()) 
//Create the doc 
doc, err := html.Parse(file) 
//Check for err when generating the doc 
check(err) 
//Look for tags with img using an anonymous function. 
var f func(*html.Node) 
f = func(n *html.Node) { 
    if n.Type == html.ElementNode && n.Data == "img" { 
     for _, img := range n.Attr { 
      if img.Key == "src" { 
       str := breakdownURL(img.Val) //Gets the ../../resource/(thing.h23.jpg) <-- That 
       //Creating a static address to add to the dynamic one 
       address := filepath.Join(filepath.Join("Resources", getFileNotExt(file)), str) 
       img.Val = address 
       break 
      } 
     } 
    } 

    for at := n.FirstChild; at != nil; at = at.NextSibling { 
     f(at) 
    } 
} 

f(doc) 

這是能夠找到的元素,並添加正確的目錄,但它只是修改此doc文件。我不知道如何將它附加到實際的文件。我唯一的想法是打開文檔作爲某種寫作方式,並將新的數據從文檔複製到文件中。任何幫助是極大的讚賞!非常感謝你花時間:)。

回答

0

您應該保存編輯後的文檔。

首先,打開文件進行讀/寫,並截斷:

file, err := os.OpenFile("sample.html", os.O_RDWR | os.O_TRUNC, 0644) 

你完成處理後,覆蓋原來的文件:

html.Render(file, doc) 
+0

我會嘗試這一點,並告訴你如何去! –

+0

我現在所處的問題是文件的寫入不正確,但我認爲這是做這件事的正確方法,謝謝! –