- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我试图对 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/
在我第一次尝试使用 Go 进行编程时,我尝试自动从 Psiu Puxa 下载可爱的壁纸。 ,根据 HTML 中帖子中的标题保存带有文件名的图像。 但是,我还没有找到如何将文本节点的值作为字符串获取。
我正在使用 github.com/moovweb/gokogiri解析 XML 文档。以下在解析 var b 时有效,但是当我在 var a (具有命名空间)上尝试相同时,我没有得到任何输出。如何使用
我正在尝试安装 gokogiri在 Windows 8 机器上按照他们的 github 页面中的说明操作: To install: sudo apt-get install libxml2-dev g
我使用的环境是MacOS Sierra上的go1.8。 代码: package main import ( "fmt" "io/ioutil" "github.com/moov
是否有相对简单的方法让 go + libxml2 + gokogiri 在 windows 上运行? 我的意思是我可能可以安装它(但目前我不能,卡在 Package libxml-2.0 was no
我是一名优秀的程序员,十分优秀!