gpt4 book ai didi

xml - Golang Gokogiri递归xpath异常

转载 作者:IT王子 更新时间:2023-10-29 00:38:00 25 4
gpt4 key购买 nike

我试图对 html 文档执行 xpath 操作。我想做一个两级 xpath 查询。 html文件“index.html”如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="head">
<div class="area">
<div class="value">10</div>
</div>
<div class="area">
<div class="value">20</div>
</div>
<div class="area">
<div class="value">30</div>
</div>
</div>
</body>
</html>

我想首先获取所有带有 class="area"的 div,然后使用 Gokogiri 在 golang 中递归获取带有 class="value"的 div。

我的go代码如下: 包主

import (
"fmt"
"io/ioutil"

"github.com/moovweb/gokogiri"
"github.com/moovweb/gokogiri/xpath"
)

func main() {
content, _ := ioutil.ReadFile("index.html")

doc, _ := gokogiri.ParseHtml(content)
defer doc.Free()

xps := xpath.Compile("//div[@class='head']/div[@class='area']")
xpw := xpath.Compile("//div[@class='value']")
ss, _ := doc.Root().Search(xps)
for _, s := range ss {
ww, _ := s.Search(xpw)
for _, w := range ww {
fmt.Println(w.InnerHtml())
}
}
}

但是,我得到的输出是奇怪的:

10
20
30
10
20
30
10
20
30

我打算得到:

10
20
30

我想递归地搜索 xpath 模式。我认为我的二级 xpath 模式有问题。看起来,我的第二级 xpath 再次在整个文档中搜索,而不是在带有 class="area"的单个 div 中搜索。我应该如何进行递归 xpath 模式搜索?如果有任何帮助,我将不胜感激。

最佳答案

来自任何节点的 XPath 搜索仍然可以搜索整个树。

如果你只想搜索子树,你可以用 . 开始表达式(假设你仍然想要 descendant-or-self),否则使用精确路径。

xps := xpath.Compile("//div[@class='head']/div[@class='area']")
xpw := xpath.Compile(".//div[@class='value']")

// this works in your example case
// xpw := xpath.Compile("div[@class='value']")
// as does this
// xpw := xpath.Compile("./div[@class='value']")

ss, _ := doc.Root().Search(xps)
for _, s := range ss {
ww, _ := s.Search(xpw)
for _, w := range ww {
fmt.Println(w.InnerHtml())
}
}

打印:

10
20
30

关于xml - Golang Gokogiri递归xpath异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25386761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com