How do I combine multiple selectors in GoQuery?

In GoQuery, which is a library for Go that brings a syntax and feature set similar to jQuery for traversing and manipulating HTML documents, you can combine multiple selectors much like you do in jQuery. GoQuery's selection methods accept a string that specifies one or more CSS selectors separated by commas. This allows you to target multiple elements across different classes, IDs, types, or attributes with a single query.

Here's an example of how you can use GoQuery to combine multiple selectors:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/PuerkitoBio/goquery"
)

func main() {
    // Example HTML document
    html := `<html>
<head><title>Multi-selectors</title></head>
<body>
    <div id="content">
        <p class="note">First note</p>
        <p class="note">Second note</p>
        <div class="message">First message</div>
    </div>
    <p class="note">Third note outside content</p>
</body>
</html>`

    // Create a goquery document from the HTML
    doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
    if err != nil {
        log.Fatal("Error loading HTTP response body. ", err)
    }

    // Combine multiple selectors with a comma
    // This will select all elements that match any of the selectors
    doc.Find(".note, .message").Each(func(i int, s *goquery.Selection) {
        // For each item found, get the text and print it
        fmt.Println(s.Text())
    })
}

In the example above, we're selecting all elements with the class .note and all elements with the class .message within the HTML document. The Find method is used with the argument ".note, .message" which tells GoQuery to look for elements that match either of the two classes.

When you run this code, you should see the following output, which includes text from both .note and .message classes:

First note
Second note
First message
Third note outside content

This demonstrates how you can combine selectors in GoQuery to select multiple distinct sets of elements with a single query. Remember that the syntax for the selectors string is the same as in CSS, so you can use all the standard CSS selector patterns.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon