Documentation
¶
Overview ¶
Package goquery implements features similar to jQuery, including the chainable syntax, to manipulate and query an HTML document.
It brings a syntax and a set of features similar to jQuery to the Go language. It is based on Go's net/html package and the CSS Selector library cascadia. Since the net/html parser returns nodes, and not a full-featured DOM tree, jQuery's stateful manipulation functions (like height(), css(), detach()) have been left off.
Also, because the net/html parser requires UTF-8 encoding, so does goquery: it is the caller's responsibility to ensure that the source document provides UTF-8 encoded HTML. See the repository's wiki for various options on how to do this.
Syntax-wise, it is as close as possible to jQuery, with the same method names when possible, and that warm and fuzzy chainable interface. jQuery being the ultra-popular library that it is, writing a similar HTML-manipulating library was better to follow its API than to start anew (in the same spirit as Go's fmt package), even though some of its methods are less than intuitive (looking at you, index()...).
It is hosted on GitHub, along with additional documentation in the README.md file: https://github.com/puerkitobio/goquery
Please note that because of the net/html dependency, goquery requires Go1.1+.
The various methods are split into files based on the category of behavior. The three dots (...) indicate that various "overloads" are available.
* array.go : array-like positional manipulation of the selection.
- Eq()
- First()
- Get()
- Index...()
- Last()
- Slice()
* expand.go : methods that expand or augment the selection's set.
- Add...()
- AndSelf()
- Union(), which is an alias for AddSelection()
* filter.go : filtering methods, that reduce the selection's set.
- End()
- Filter...()
- Has...()
- Intersection(), which is an alias of FilterSelection()
- Not...()
* iteration.go : methods to loop over the selection's nodes.
- Each()
- EachWithBreak()
- Map()
* manipulation.go : methods for modifying the document
- After...()
- Append...()
- Before...()
- Clone()
- Empty()
- Prepend...()
- Remove...()
- ReplaceWith...()
- Unwrap()
- Wrap...()
- WrapAll...()
- WrapInner...()
* property.go : methods that inspect and get the node's properties values.
- Attr*(), RemoveAttr(), SetAttr()
- AddClass(), HasClass(), RemoveClass(), ToggleClass()
- Html()
- Length()
- Size(), which is an alias for Length()
- Text()
* query.go : methods that query, or reflect, a node's identity.
- Contains()
- Is...()
* traversal.go : methods to traverse the HTML document tree.
- Children...()
- Contents()
- Find...()
- Next...()
- Parent[s]...()
- Prev...()
- Siblings...()
* type.go : definition of the types exposed by goquery.
- Document
- Selection
- Matcher
* utilities.go : definition of helper functions (and not methods on a *Selection) that are not part of jQuery, but are useful to goquery.
- NodeName
- OuterHtml
Example ¶
This example scrapes the reviews shown on the home page of metalsucks.net.
package main
import (
"fmt"
"log"
"net/http"
"github.com/PuerkitoBio/goquery"
)
func main() {
// Request the HTML page.
res, err := http.Get("http://metalsucks.net")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}
// Load the HTML document
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
// Find the review items
doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
// For each item found, get the band and title
band := s.Find("a").Text()
title := s.Find("i").Text()
fmt.Printf("Review %d: %s - %s\n", i, band, title)
})
// To see the output of the Example while running the test suite (go test), simply
// remove the leading "x" before Output on the next line. This will cause the
// example to fail (all the "real" tests should pass).
// xOutput: voluntarily fail the Example output.
}
Output:
Index ¶
- Constants
- func Map[E any](s *Selection, f func(int, *Selection) E) (result []E)
- func NodeName(s *Selection) string
- func OuterHtml(s *Selection) (string, error)
- func Render(w io.Writer, s *Selection) error
- func Text(s *Selection, opts *TextOptions) string
- type Document
- type Matcher
- type Selection
- func (s *Selection) Add(selector string) *Selection
- func (s *Selection) AddBack() *Selection
- func (s *Selection) AddBackFiltered(selector string) *Selection
- func (s *Selection) AddBackMatcher(m Matcher) *Selection
- func (s *Selection) AddClass(class ...string) *Selection
- func (s *Selection) AddMatcher(m Matcher) *Selection
- func (s *Selection) AddNodes(nodes ...*html.Node) *Selection
- func (s *Selection) AddSelection(sel *Selection) *Selection
- func (s *Selection) After(selector string) *Selection
- func (s *Selection) AfterHtml(htmlStr string) *Selection
- func (s *Selection) AfterMatcher(m Matcher) *Selection
- func (s *Selection) AfterNodes(ns ...*html.Node) *Selection
- func (s *Selection) AfterSelection(sel *Selection) *Selection
- func (s *Selection) AndSelf() *Selection
- func (s *Selection) Append(selector string) *Selection
- func (s *Selection) AppendHtml(htmlStr string) *Selection
- func (s *Selection) AppendMatcher(m Matcher) *Selection
- func (s *Selection) AppendNodes(ns ...*html.Node) *Selection
- func (s *Selection) AppendSelection(sel *Selection) *Selection
- func (s *Selection) Attr(attrName string) (string, bool)
- func (s *Selection) AttrOr(attrName, defaultValue string) string
- func (s *Selection) Before(selector string) *Selection
- func (s *Selection) BeforeHtml(htmlStr string) *Selection
- func (s *Selection) BeforeMatcher(m Matcher) *Selection
- func (s *Selection) BeforeNodes(ns ...*html.Node) *Selection
- func (s *Selection) BeforeSelection(sel *Selection) *Selection
- func (s *Selection) Children() *Selection
- func (s *Selection) ChildrenFiltered(selector string) *Selection
- func (s *Selection) ChildrenMatcher(m Matcher) *Selection
- func (s *Selection) Clone() *Selection
- func (s *Selection) Closest(selector string) *Selection
- func (s *Selection) ClosestMatcher(m Matcher) *Selection
- func (s *Selection) ClosestNodes(nodes ...*html.Node) *Selection
- func (s *Selection) ClosestSelection(sel *Selection) *Selection
- func (s *Selection) Contains(n *html.Node) bool
- func (s *Selection) Contents() *Selection
- func (s *Selection) ContentsFiltered(selector string) *Selection
- func (s *Selection) ContentsMatcher(m Matcher) *Selection
- func (s *Selection) Each(f func(int, *Selection)) *Selection
- func (s *Selection) EachIter() iter.Seq2[int, *Selection]
- func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection
- func (s *Selection) Empty() *Selection
- func (s *Selection) End() *Selection
- func (s *Selection) Eq(index int) *Selection
- func (s *Selection) Filter(selector string) *Selection
- func (s *Selection) FilterFunction(f func(int, *Selection) bool) *Selection
- func (s *Selection) FilterMatcher(m Matcher) *Selection
- func (s *Selection) FilterNodes(nodes ...*html.Node) *Selection
- func (s *Selection) FilterSelection(sel *Selection) *Selection
- func (s *Selection) Find(selector string) *Selection
- func (s *Selection) FindMatcher(m Matcher) *Selection
- func (s *Selection) FindNodes(nodes ...*html.Node) *Selection
- func (s *Selection) FindSelection(sel *Selection) *Selection
- func (s *Selection) First() *Selection
- func (s *Selection) Get(index int) *html.Node
- func (s *Selection) Has(selector string) *Selection
- func (s *Selection) HasClass(class string) bool
- func (s *Selection) HasMatcher(m Matcher) *Selection
- func (s *Selection) HasNodes(nodes ...*html.Node) *Selection
- func (s *Selection) HasSelection(sel *Selection) *Selection
- func (s *Selection) Html() (ret string, e error)
- func (s *Selection) Index() int
- func (s *Selection) IndexMatcher(m Matcher) int
- func (s *Selection) IndexOfNode(node *html.Node) int
- func (s *Selection) IndexOfSelection(sel *Selection) int
- func (s *Selection) IndexSelector(selector string) int
- func (s *Selection) Intersection(sel *Selection) *Selection
- func (s *Selection) Is(selector string) bool
- func (s *Selection) IsFunction(f func(int, *Selection) bool) bool
- func (s *Selection) IsMatcher(m Matcher) bool
- func (s *Selection) IsNodes(nodes ...*html.Node) bool
- func (s *Selection) IsSelection(sel *Selection) bool
- func (s *Selection) Last() *Selection
- func (s *Selection) Length() int
- func (s *Selection) Map(f func(int, *Selection) string) (result []string)
- func (s *Selection) Next() *Selection
- func (s *Selection) NextAll() *Selection
- func (s *Selection) NextAllFiltered(selector string) *Selection
- func (s *Selection) NextAllMatcher(m Matcher) *Selection
- func (s *Selection) NextFiltered(selector string) *Selection
- func (s *Selection) NextFilteredUntil(filterSelector, untilSelector string) *Selection
- func (s *Selection) NextFilteredUntilMatcher(filter, until Matcher) *Selection
- func (s *Selection) NextFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
- func (s *Selection) NextFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
- func (s *Selection) NextMatcher(m Matcher) *Selection
- func (s *Selection) NextMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
- func (s *Selection) NextMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
- func (s *Selection) NextUntil(selector string) *Selection
- func (s *Selection) NextUntilMatcher(m Matcher) *Selection
- func (s *Selection) NextUntilNodes(nodes ...*html.Node) *Selection
- func (s *Selection) NextUntilSelection(sel *Selection) *Selection
- func (s *Selection) Not(selector string) *Selection
- func (s *Selection) NotFunction(f func(int, *Selection) bool) *Selection
- func (s *Selection) NotMatcher(m Matcher) *Selection
- func (s *Selection) NotNodes(nodes ...*html.Node) *Selection
- func (s *Selection) NotSelection(sel *Selection) *Selection
- func (s *Selection) Parent() *Selection
- func (s *Selection) ParentFiltered(selector string) *Selection
- func (s *Selection) ParentMatcher(m Matcher) *Selection
- func (s *Selection) Parents() *Selection
- func (s *Selection) ParentsFiltered(selector string) *Selection
- func (s *Selection) ParentsFilteredUntil(filterSelector, untilSelector string) *Selection
- func (s *Selection) ParentsFilteredUntilMatcher(filter, until Matcher) *Selection
- func (s *Selection) ParentsFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
- func (s *Selection) ParentsFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
- func (s *Selection) ParentsMatcher(m Matcher) *Selection
- func (s *Selection) ParentsMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
- func (s *Selection) ParentsMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
- func (s *Selection) ParentsUntil(selector string) *Selection
- func (s *Selection) ParentsUntilMatcher(m Matcher) *Selection
- func (s *Selection) ParentsUntilNodes(nodes ...*html.Node) *Selection
- func (s *Selection) ParentsUntilSelection(sel *Selection) *Selection
- func (s *Selection) Prepend(selector string) *Selection
- func (s *Selection) PrependHtml(htmlStr string) *Selection
- func (s *Selection) PrependMatcher(m Matcher) *Selection
- func (s *Selection) PrependNodes(ns ...*html.Node) *Selection
- func (s *Selection) PrependSelection(sel *Selection) *Selection
- func (s *Selection) Prev() *Selection
- func (s *Selection) PrevAll() *Selection
- func (s *Selection) PrevAllFiltered(selector string) *Selection
- func (s *Selection) PrevAllMatcher(m Matcher) *Selection
- func (s *Selection) PrevFiltered(selector string) *Selection
- func (s *Selection) PrevFilteredUntil(filterSelector, untilSelector string) *Selection
- func (s *Selection) PrevFilteredUntilMatcher(filter, until Matcher) *Selection
- func (s *Selection) PrevFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
- func (s *Selection) PrevFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
- func (s *Selection) PrevMatcher(m Matcher) *Selection
- func (s *Selection) PrevMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
- func (s *Selection) PrevMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
- func (s *Selection) PrevUntil(selector string) *Selection
- func (s *Selection) PrevUntilMatcher(m Matcher) *Selection
- func (s *Selection) PrevUntilNodes(nodes ...*html.Node) *Selection
- func (s *Selection) PrevUntilSelection(sel *Selection) *Selection
- func (s *Selection) Remove() *Selection
- func (s *Selection) RemoveAttr(attrName string) *Selection
- func (s *Selection) RemoveClass(class ...string) *Selection
- func (s *Selection) RemoveFiltered(selector string) *Selection
- func (s *Selection) RemoveMatcher(m Matcher) *Selection
- func (s *Selection) ReplaceWith(selector string) *Selection
- func (s *Selection) ReplaceWithHtml(htmlStr string) *Selection
- func (s *Selection) ReplaceWithMatcher(m Matcher) *Selection
- func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection
- func (s *Selection) ReplaceWithSelection(sel *Selection) *Selection
- func (s *Selection) SetAttr(attrName, val string) *Selection
- func (s *Selection) SetHtml(htmlStr string) *Selection
- func (s *Selection) SetText(text string) *Selection
- func (s *Selection) Siblings() *Selection
- func (s *Selection) SiblingsFiltered(selector string) *Selection
- func (s *Selection) SiblingsMatcher(m Matcher) *Selection
- func (s *Selection) Size() int
- func (s *Selection) Slice(start, end int) *Selection
- func (s *Selection) Text() string
- func (s *Selection) ToggleClass(class ...string) *Selection
- func (s *Selection) Union(sel *Selection) *Selection
- func (s *Selection) Unwrap() *Selection
- func (s *Selection) Wrap(selector string) *Selection
- func (s *Selection) WrapAll(selector string) *Selection
- func (s *Selection) WrapAllHtml(htmlStr string) *Selection
- func (s *Selection) WrapAllMatcher(m Matcher) *Selection
- func (s *Selection) WrapAllNode(n *html.Node) *Selection
- func (s *Selection) WrapAllSelection(sel *Selection) *Selection
- func (s *Selection) WrapHtml(htmlStr string) *Selection
- func (s *Selection) WrapInner(selector string) *Selection
- func (s *Selection) WrapInnerHtml(htmlStr string) *Selection
- func (s *Selection) WrapInnerMatcher(m Matcher) *Selection
- func (s *Selection) WrapInnerNode(n *html.Node) *Selection
- func (s *Selection) WrapInnerSelection(sel *Selection) *Selection
- func (s *Selection) WrapMatcher(m Matcher) *Selection
- func (s *Selection) WrapNode(n *html.Node) *Selection
- func (s *Selection) WrapSelection(sel *Selection) *Selection
- type TextOptions
Examples ¶
Constants ¶
const ( // ToEnd is a special index value that can be used as end index in a call // to Slice so that all elements are selected until the end of the Selection. // It is equivalent to passing (*Selection).Length(). ToEnd = maxInt )
Variables ¶
This section is empty.
Functions ¶
func Map ¶ added in v1.9.0
Map is the generic version of Selection.Map, allowing any type to be returned.
func NodeName ¶ added in v1.0.0
NodeName returns the node name of the first element in the selection. It tries to behave in a similar way as the DOM's nodeName property (https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName).
Go's net/html package defines the following node types, listed with the corresponding returned value from this function:
ErrorNode : #error TextNode : #text DocumentNode : #document ElementNode : the element's tag name CommentNode : #comment DoctypeNode : the name of the document type
func OuterHtml ¶ added in v1.0.0
OuterHtml returns the outer HTML rendering of the first item in the selection - that is, the HTML including the first element's tag and attributes.
Unlike Html, this is a function and not a method on the Selection, because this is not a jQuery method (in javascript-land, this is a property provided by the DOM).
func Render ¶ added in v1.8.0
Render renders the HTML of the first item in the selection and writes it to the writer. It behaves the same as OuterHtml but writes to w instead of returning the string.
func Text ¶ added in v1.13.0
func Text(s *Selection, opts *TextOptions) string
Text returns the combined text contents of the nodes in the selection, including their descendants, in document order. It is a package-level function - and not a method on the Selection, because it is not part of the jQuery API - that offers control over how the text of distinct text nodes is joined and which text nodes are included, in the same spirit as Python's BeautifulSoup get_text.
With a nil opts (or a zero-value TextOptions), Text behaves like calling the Selection.Text method on the selection. Setting TextOptions.Separator inserts a separator between the text nodes, Trim strips the surrounding whitespace of each text node (dropping the ones that become empty), and Keep filters which text nodes contribute to the result.
Example ¶
This example shows how to use the goquery.Text function to extract clean, human-readable text from a selection, similar to BeautifulSoup's get_text.
package main
import (
"fmt"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
)
func main() {
page := `
Hello
world
`
doc, err := goquery.NewDocumentFromReader(strings.NewReader(page))
if err != nil {
log.Fatal(err)
}
// Trim each text node, join the remaining ones with a space, and skip the
// text of
