几天来我一直在试图解决这个问题,甚至已经用尽了最有效的谷歌搜索。我一直试图做的是打开一个 HTML 类型的文件,并使用 Go 的库( http://golang.org/x/net/html )将 img 标签及其源修改为已知的目录和文件集。到目前为止,我已经能够使用它找到元素,
//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)
这已经能够找到元素并附加正确的目录,但它只是修改此文档文件。我不知道如何将其附加到实际文件中。我唯一的想法是以某种书写方式打开文档,并将新数据从文档复制到文件中。任何帮助是极大的赞赏!非常感谢您抽出宝贵时间:)。
最佳答案
您一定要保存编辑过的文档。
首先,打开文件进行读/写并截断:
file, err := os.OpenFile("sample.html", os.O_RDWR | os.O_TRUNC, 0644)
处理完成后,覆盖原始文件:
html.Render(file, doc)
关于html - 如何使用 Go 修改 HTML 文件的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42324166/