How to extract JSON data from HTML using goquery in Golang?

WBOY
Release: 2024-06-02 09:23:57
Original
1049 people have browsed it

Methods to use goquery to extract JSON data from HTML in Go are: Install goquery library: go get -u github.com/PuerkitoBio/goquery Load HTML document: goquery.NewDocument(htmlURL) Select elements containing JSON data: doc .Find(selector) gets JSON data: jsonDataElement.Text()

如何在 Golang 中使用 goquery 从 HTML 中提取 JSON 数据?

How to use goquery to extract JSON data from HTML in Golang?

Goquery is a Go library that allows you to parse, manipulate, and query HTML in a jQuery-like manner. It is useful for extracting JSON data from HTML.

Installation goquery

go get -u github.com/PuerkitoBio/goquery
Copy after login

Practical case

Let us consider a practical case of extracting JSON data from an HTML page. Suppose we have a page that contains the following JSON data:

<div id="json-data">
  {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
  }
</div>
Copy after login

Using goquery, we can easily extract this JSON data:

package main

import (
    "fmt"
    "log"

    "github.com/PuerkitoBio/goquery"
)

func main() {
    // 加载 HTML 文档
    doc, err := goquery.NewDocument("https://example.com/page.html")
    if err != nil {
        log.Fatal(err)
    }

    // 从 HTML 中选择包含 JSON 数据的元素
    jsonDataElement := doc.Find("#json-data")

    // 获取 JSON 数据
    jsonData := jsonDataElement.Text()

    // 打印 JSON 数据
    fmt.Println(jsonData)
}
Copy after login

Output:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}
Copy after login

Conclusion

Extracting JSON data from HTML using goquery is very simple. Just load the HTML document, select the element containing the JSON data, and get the data. This is useful for automating tasks and extracting data from the network.

The above is the detailed content of How to extract JSON data from HTML using goquery in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!