magical internet,
I am trying to filter elements from an html string using "github.com/PuerkitoBio/goquery". Unfortunately, the filter function does not return the expected result. I would have expected to get back a list of all articles but instead, ... nothing.
package main
import (
"fmt"
"os"
"strings"
"github.com/PuerkitoBio/goquery"
)
var html = `
<section>
<article>
<h1>Article 1</h1>
<p>Text for article #1</p>
</article>
<article>
<h1>Article 2</h1>
<p>Text for article #2</p>
</article>
</section>
`
func main() {
qHtml, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
panic(err)
}
articles := qHtml.Filter(`article`)
fmt.Println(articles.Nodes)
goquery.Render(os.Stdout, articles)
}
CodePudding user response:
You're trying to filter a selection that is empty.
From what I see you're trying to do in your question, you could simply replace the Filter
with Find
. So in your case it would be:
articles := qHtml.Find("article")
Once you have a selection containing elements, then you can use Filter
. So, for example, to get the second article, you could do :
articles := qHtml.Find("article").Filter(":nth-child(2)")
To read more about Filter
, check out these resources:
PS
: You can also combine it in single selector to Find
specific article
articles := qHtml.Find("article:nth-child(2)")
CodePudding user response:
As per doc
Filter
reduces the set of matched elements to those that match the selector string. It returns a new Selection object for this subset of matching elements.
Since before Filter
you are not matching anything that's why you got empty result since Filter
got no matched elements.
You have to first match elements or get Selection
set of nodes before you can apply Filter
To solve the issue instead of Filter
you can use Find
or FindMatcher
searchStr := `article`
articles := qHtml.Find(searchStr)
articles := qHtml.FindMatcher(goquery.Single(searchStr))