我想从 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/