如何在 Go 中解析和生成 HTML
借助 Golang 的 html 和 html/template 包,解析和生成 HTML 是轻而易举的事。
解析是分析和解释文档的结构。解析过程可以包括从文档中提取特定元素、属性或数据,并验证文档格式良好,同时遵循特定标准或规则。解析主要用于从网页中提取数据或在将网页显示给用户之前操纵网页的结构。
Go 提供了用于处理文档的包,包括网页中常用的 HTML 和 XML 格式。 html 包提供了标记和解析 HTML 的函数。
HTML 包
html 包提供了一个兼容 HTML5 的分词器和解析器,用于解析和操作 HTML 文档、遍历解析树以及操作树结构。 html 包是 Go 标准库的内置包。
html 包的主要功能之一是 Parse 函数,它可以解析 HTML 文档并返回解析树的根节点,从中您可以使用诸如FirstChild 和 NextSibling 用于导航树并从文档中提取信息。该包还提供了ParseFragment函数来解析HTML文档的片段。
EscapeString 函数可以方便地转义字符串中的特殊字符,以便更安全地包含在 HTML 中;您可以使用此功能通过将特殊字符转换为其相应的 HTML 实体来防止跨站脚本 (XSS) 攻击。
要开始使用 html 包,您可以将该包导入到 Go 项目文件中。
import "golang.org/x/net/html"
html 包不提供任何生成 HTML 的函数。相反,您可以使用 html/template 包,它提供了一组用于生成 HTML 模板的函数。 html/template 包提供了一个函数template.HTMLEscape,用于将转义版本的 HTML 写入响应编写器。
html/template 包也是标准库的一部分,以下是导入该包的方法。
import "html/template"
html 包是 Go 生态系统中最常用的模板包,支持各种操作和数据类型。
在 Go 中解析 HTML
html 包的 Parse 功能有助于解析 HTML 文本和文档。 Parse 函数接受一个 io.Reader 实例,因为它是包含文件文档的第一个参数和一个 *html.Node 实例,它是HTML 文档的根节点
以下是如何使用 Parse 函数来解析网页并返回网页上的所有 URL。
import (
"fmt"
"golang.org/x/net/html"
"net/http"
)
func main() {
// Send an HTTP GET request to the example.com web page
resp, err := http.Get("https://www.example.com")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// Use the html package to parse the response body from the request
doc, err := html.Parse(resp.Body)
if err != nil {
fmt.Println("Error:", err)
return
}
// Find and print all links on the web page
var links []string
var link func(*html.Node)
link = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key == "href" {
// adds a new link entry when the attribute matches
links = append(links, a.Val)
}
}
}
// traverses the HTML of the webpage from the first child node
for c := n.FirstChild; c != nil; c = c.NextSibling {
link(c)
}
}
link(doc)
// loops through the links slice
for _, l := range links {
fmt.Println("Link:", l)
}
}
main 函数使用 http 包的 Get 函数向网站发送 HTTP GET 请求,并检索页面响应正文。 html 包的 Parse 函数解析响应正文并返回 HTML 文档。
links 变量是保存网页 URL 的字符串片段。 link 函数接收对 html 包的 Node 方法的指针引用,以及对 html 包的 Key 方法的指针引用。节点中的属性实例返回指定属性(在本例中为 href)中包含的数据。该函数使用 NextSibling 方法从 FirstChild 节点遍历文档,以打印网页上的每个 URL。最后,for 循环打印 links 切片中的所有 URL。
这是操作的结果。
在 Go 中生成 HTML
html/template包提供了一组用于安全高效地解析和执行HTML模板的函数。该包设计为与 html 包结合使用,后者提供了解析和操作 HTML 的功能。
您可以使用 html/template 包生成用于服务器端渲染的 HTML。生成 HTML 对于许多用例来说都很方便,例如发送电子邮件、服务器端前端渲染等等。您可以使用内置的 Go 数据类型(例如地图和结构)来交互和操作网页的 HTML。
您需要了解 Go HTML 模板语法才能使用 html/template 包成功生成 HTML。
import (
"html/template"
"os"
)
type webPage struct {
Title string
Heading string
Text string
}
func main() {
// Define the template
tmpl := `
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Heading}}</h1>
<p>{{.Text}}</p>
</body>
</html>`
// Define the data to be used in the template
web := webPage{
Title: "An Example Page",
Heading: "Welcome to my website!",
Text: "This is the home page of my website.",
}
// Create a new template and parse the template string
t, err := template.New("webpage").Parse(tmpl)
if err != nil {
panic(err)
}
// Execute the template and write the result to stdout
err = t.Execute(os.Stdout, web )
if err != nil {
panic(err)
}
}
tmpl 变量保存 HTML 字符串。 HTML 字符串使用 Go 模板语法来定义页面标题、h1 标题和文本段落。 webPage 结构通过 Title、Heading 和 Text 字段定义网页的数据字段。
模板包的New函数的Parse方法使用模板字符串创建并解析一个新模板。新模板实例的执行函数使用结构体实例中的数据执行模板,并将结果返回到标准输出(在本例中,它将结果打印到控制台)。
使用 Go 构建 Web 应用程序
学习使用 Go 解析和生成 HTML 是朝着使用 Go 构建更复杂的 Web 应用程序的正确方向迈出的一步。您可以使用 Gin 和 Echo 等框架以及 Gorilla Mux 和 Chi Router 等路由器来构建 Web 应用程序的服务器端。
这些包构建在 net/http 包(Go 中用于与 HTTP 交互的内置包)之上,并抽象了在 Go 中设置服务器和路由器的复杂性。


