dongqiongzheng0615 2017-02-19 06:00
浏览 220
已采纳

如何使用Go修改HTML文件的元素?

I've been trying to figure this out for a few days and I've kind of exhausted even the most effective of google searching. What I've been trying to do is to open a file of the type HTML and with Go's library (http://golang.org/x/net/html) modify the img tags and their source to a known directory and set of files. So far I've been able to find the elements using this,

//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)

That's been able to find the elements and append the correct directory but it's only modifying this doc file. I have no clue how to append it to the actual file. The only thought that I have is opening the doc as some kind of writing way and copying the new data from the doc to the file. Any help is greatly appreciated! Thank you so much for taking your time :).

  • 写回答

1条回答 默认 最新

  • doupo5861 2017-02-19 10:44
    关注

    You should definitely save the edited document.

    First, open the file for read/write and truncate:

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

    And after you finish processing, override the original file:

    html.Render(file, doc)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?