html - 使用Go访问DOM并获取数据

标签 html http go dom document

我想从 URL 访问 HTML 文档标签,例如,我有以下网页:

https://example.com/

我想要 h1 的内部内容标签,“示例域”:

<h1>Example Domain</h1>

同样适用于<p>标签:

<p> More information...</p>

然后使用不同标签的值创建一个结构:

type Example struct {
   foo string
   bar string
}

Example.foo = *h1 tag content*
Example.bar = *p tag content*

这可能吗?

最佳答案

我个人会使用goquery为此:

// Request the HTML page.
res, err := http.Get("https://example.com/")
if err != nil {
    log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
    log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
}

// Load the HTML document
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
    log.Fatal(err)
}

h1 := doc.Find("h1").First().Text()
p := doc.Find("p").First().Text()

type Example struct {
    foo string
    bar string
}

e := Example{ foo: h1, bar: p }

关于html - 使用Go访问DOM并获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73085653/

相关文章:

javascript - 为什么 DOMParser 不保留已解析 DOM 的内联样式?

html - 无论数量多少,都保持 div 始终水平居中

java - 使用 Java Servlet 访问 post 变量

ssl - 带有证书、私钥和密码短语的 TLS

go - Mac安装beego失败

google-app-engine - 如何使用 gcloud 将具有依赖关系的 golang 应用程序部署到应用程序引擎?

javascript - Jquery,<a> 元素上的每个函数中的 url 保持不变(UserScript)

html - 使用 Tab 键时看到复选标记上的轮廓

android - ASIHTTPRequest 等效于 Android 或任何 HTTP 请求管理器/包装器?

http - 监控、模拟、创建 HTTP 数据包