Skip to content

htmlqueryvscheerio

MIT 8 1 739
58.1 thousand (month) Feb 07 2019 v1.3.3(20 days ago)
28,608 13 46 MIT
Oct 08 2011 38.3 million (month) 1.0.0(2 months ago)

htmlquery is a Go library that allows you to parse and extract data from HTML documents using XPath expressions. It provides a simple and intuitive API for traversing and querying the HTML tree structure, and it is built on top of the popular Goquery library.

cheerio is a popular JavaScript library that allows you to interact with and manipulate HTML and XML documents in a similar way to how you would with jQuery in a browser. It is a fast, flexible, and lean implementation of core jQuery designed specifically for the server.

One of the main benefits of using cheerio is that it allows you to use jQuery-like syntax to navigate and m anipulate the Document Object Model (DOM) of an HTML or XML document, making it easy to work with.

cheerio supports CSS selectors though not XPath.

Example Use


package main

import (
  "fmt"
  "log"

  "github.com/antchfx/htmlquery"
)

func main() {
  // Parse the HTML string
  doc, err := htmlquery.Parse([]byte(`
    <html>
      <body>
        <h1>Hello, World!</h1>
        <ul>
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </ul>
      </body>
    </html>
  `))
  if err != nil {
    log.Fatal(err)
  }

  // Extract the text of the first <h1> element
  h1 := htmlquery.FindOne(doc, "//h1")
  fmt.Println(htmlquery.InnerText(h1)) // "Hello, World!"

  // Extract the text of all <li> elements
  lis := htmlquery.Find(doc, "//li")
  for _, li := range lis {
    fmt.Println(htmlquery.InnerText(li))
  }
  // "Item 1"
  // "Item 2"
  // "Item 3"
}
const cheerio = require('cheerio');
const $ = cheerio.load('<html><head><title>My title</title></head><body><h1 class='name'>Hello World!</h1></body></html>');
// use css selectors
console.log($('title').text()); // My title
console.log($('.name').text()); // Hello World!

// select multiple elements
const $ = cheerio.load('<html><body><ul><li>item 1</li><li>item 2</li></ul></body></html>');
$('li').each(function(i, elem) {
  console.log($(this).text());
});

// modify elements
const $ = cheerio.load('<html><body><h1>Hello World!</h1></body></html>');
$('h1').text('Hello, Cheerio!');
console.log($.html());

Alternatives / Similar


Was this page helpful?