对于我第一次尝试使用Go编程,我试图自动从浦沙下载可爱的壁纸,根据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>我的围棋包:
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的源代码,并找到了关于胁迫字符串的方法/指令,但我很迷茫,希望得到任何提示。
发布于 2015-09-03 19:42:24
这里有一个xml.Node结构数组。您需要访问该数组中包含的节点。
如果你确定你有一个元素,那么你可以
postTitleRes[0].Content()或者捕获所有这些节点:
for _, node := range postTitleRes {
fmt.Printf("%T: %v\n", node, node.Content())
}您可以看到,一旦您有了单数的Content函数,xml.Node函数就应该对您可用。定义。
https://stackoverflow.com/questions/32383662
复制相似问题