Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

元素属性值输出问题 #4

Closed
ghost opened this issue Mar 8, 2017 · 8 comments
Closed

元素属性值输出问题 #4

ghost opened this issue Mar 8, 2017 · 8 comments

Comments

@ghost
Copy link

ghost commented Mar 8, 2017

一直没明白如何输出://img/@src 这样的xpath规则的结果。
我期望的是输出元素img的属性src的值,请帮助我,谢谢!

@zhengchun
Copy link
Contributor

xpath库目前并不支持直接输出@属性值,它默认返回是包括指定@的元素,也就是一个Node对象,得到对象后你才能获取它的@属性值。

elem := htmlquery.FindOne(root, `//img/@src`)
fmt.Println(htmlquery.SelectAttr(elem,"src"))

类似于这个:
xquery#2

@ghost
Copy link
Author

ghost commented Mar 8, 2017

OK,这个问题我大概调试出来了。

// FindEach searches the html.Node and calls functions cb.
func FindEach(top *html.Node, expr string, cb func(int, NodeNavigator, *html.Node)) {
	t := Select(CreateXPathNavigator(top), expr)
	i := 0
	for t.MoveNext() {
		cb(i, t.Current().(*htmlNodeNavigator), (t.Current().(*htmlNodeNavigator)).curr)
		i++
	}
}

我将htmlNodeNavigator暴露出来,然后就能直接输出值了。

@ghost
Copy link
Author

ghost commented Mar 8, 2017

实际上是支持输出@属性值的,感谢作者的付出!

@zhengchun
Copy link
Contributor

感谢支持 😄

@ghost
Copy link
Author

ghost commented Mar 8, 2017

我的测试代码:

func TestXPathAttribute(t *testing.T) {
	FindEach(doc, "//a/@href", func(i int, nv NodeNavigator, node *html.Node) {
		t.Log(i, nv.Value())
	})
}

@zhengchun
Copy link
Contributor

Hi, @gofmt ,向使用者暴露NodeNavigator可能会造成用户的困惑,并在方法的使用上会更加复杂。

你的这个问题关于直接输出@属性值的,我之前有考虑过,实现一个Compile方法,并返回指定XPath查询的值(它可能是数字,可能是字符串,也可以是一个Node列表)。e5682c1#diff-04c6e90faac2675aa89e2176d2eec7d8L120

@ghost
Copy link
Author

ghost commented Mar 8, 2017

OK,期待!

@zhengchun
Copy link
Contributor

expr, err := xpath.Compile("//img/@src")
val := expr.Evaluate(nav)
switch typ := val.(type) {
case *xpath.NodeIterator:
    for typ.MoveNext() {
	fmt.Println(typ.Current().Value()) // output @src value
    }
}

xpath_testL184
@gofmt,最新包已经能够支持@值的输出,这个Issue将关闭。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant