使用Go官方的html库解析HTML图片链接

本文将使用Go语言的官方html库解析HTML文档,并提取其中图片标签的src属性值,获取图片链接。我们将以一个实际案例为例,展示如何使用代码提取图片链接。

1. 准备工作

首先,我们需要导入html库和net/http库,用于解析HTML文档和发送HTTP请求。

import (
    "fmt"
    "golang.org/x/net/html"
    "net/http"
)

2. 获取HTML文档

我们将使用net/http库发送一个GET请求,获取目标HTML文档。这里我们以https://zh.moegirl.org.cn/%E9%9B%AA%E7%8B%90%E6%A1%91为例。

resp, err := http.Get("https://zh.moegirl.org.cn/%E9%9B%AA%E7%8B%90%E6%A1%91")
if err != nil {
    panic(err)
}
defer resp.Body.Close()

3. 解析HTML文档

使用html.Parse函数解析获取的HTML文档,生成一个html.Node类型的根节点。

doc, err := html.Parse(resp.Body)
if err != nil {
    panic(err)
}

4. 遍历节点寻找图片标签

我们定义一个递归函数findImg,用于遍历HTML节点树,查找img标签,并提取其src属性值。

var findImg func(*html.Node)
findImg = func(n *html.Node) {
    if n.Type == html.ElementNode && n.Data == "img" {
        for _, attr := range n.Attr {
            if attr.Key == "src" {
                fmt.Println(attr.Val)
            }
        }
    }
    for c := n.FirstChild; c != nil; c = c.NextSibling {
        findImg(c)
    }
}

5. 执行解析并输出结果

最后,调用findImg函数,传入根节点doc,开始遍历解析HTML文档。

findImg(doc)

完整代码

package main

import (
    "fmt"
    "golang.org/x/net/html"
    "net/http"
)

func main() {
    resp, err := http.Get("https://zh.moegirl.org.cn/%E9%9B%AA%E7%8B%90%E6%A1%91")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    doc, err := html.Parse(resp.Body)
    if err != nil {
        panic(err)
    }

    var findImg func(*html.Node)
    findImg = func(n *html.Node) {
        if n.Type == html.ElementNode && n.Data == "img" {
            for _, attr := range n.Attr {
                if attr.Key == "src" {
                    fmt.Println(attr.Val)
                }
            }
        }
        for c := n.FirstChild; c != nil; c = c.NextSibling {
            findImg(c)
        }
    }

    findImg(doc)
}

输出结果

https://img.moegirl.org.cn/common/thumb/5/5d/%E9%9B%AA%E7%8B%90%E6%A1%91%E7%9C%8B%E6%9D%BF.png/280px-%E9%9B%AA%E7%8B%90%E6%A1%91%E7%9C%8B%E6%9D%BF.png

小结

本文介绍了使用Go语言官方html库解析HTML文档并提取图片链接的具体步骤。你可以根据这个例子,进一步修改代码,提取其他类型的HTML元素的信息。

希望本文对你有所帮助!

Go语言解析HTML提取图片链接实战教程

原文地址: https://www.cveoy.top/t/topic/jx0O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录