如何使用 Gokogiri 将文本节点转换为 Go 中的字符串?

How can I convert a text node to a string in Go with Gokogiri?

我第一次尝试使用 Go 进行编程,我尝试自动从 Psiu Puxa 下载可爱的壁纸,并根据 HTML 中帖子的标题保存图像。

但是,我还没有找到如何将文本节点的值作为字符串获取。

示例HTML,简化:

<div class="post">
    <a class="w-inline-block post-name-link" href="/posts/mars-30">
        <h4>#80 Martian Landscape</h4>
    </a>
</div>
<div class="post">
    <a class="w-inline-block post-name-link" href="#">
        <h4><strong>#79 MARTIAN terrain</strong></h4>
    </a>
</div>

我的 Go 包:

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
    "github.com/moovweb/gokogiri"
)

func main() {
    resp, _ := http.Get("http://psiupuxa3.webflow.io/")
    page, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()

    doc, _ := gokogiri.ParseHtml(page)
    res, _ := doc.Search("//div[@class='post']")
    defer doc.Free()

    for i := range res {
        postTitleRes, _ := res[i].Search("a[contains(@class,'post-name-link')]//text()")
        fmt.Printf("%T: %v\n", postTitleRes, postTitleRes)
    }

}

结果:

[]xml.Node: [#80 Martian Landscape]
[]xml.Node: [#79 MARTIAN terrain]
[]xml.Node: [#78 MARTIAN TERRAIN]

如何获取#79 MARTIAN terrain等字符串,以便以后保存文件时使用?

我试过 postTitle := postTitleRes.String(),但该方法显然不适用于 xml.Node。我花了一些时间查看 Gokogiri 的源代码,发现 methods/instructions 关于强制转换为字符串,但我很迷茫,希望得到任何指点。

那里有一个 xml.Node 结构数组。您需要访问该数组中包含的节点。

如果你确定你有一个元素,那么你可以

postTitleRes[0].Content()

或捕获所有这些节点:

for _, node := range postTitleRes {
    fmt.Printf("%T: %v\n", node, node.Content())
}

您可以看到,Content 函数在您拥有单数 xml.Node 后应该可用。 Definition.