猿问

使用 Go 访问 DOM 并获取数据

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


https://example.com/


h1我想要标签“Example Domain”中的内部内容:


<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*

这可能吗?


慕仙森
浏览 121回答 1
1回答

HUX布斯

我个人会为此使用goquery:// Request the HTML page.res, err := http.Get("https://example.com/")if err != nil {&nbsp; &nbsp; log.Fatal(err)}defer res.Body.Close()if res.StatusCode != 200 {&nbsp; &nbsp; log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)}// Load the HTML documentdoc, err := goquery.NewDocumentFromReader(res.Body)if err != nil {&nbsp; &nbsp; log.Fatal(err)}h1 := doc.Find("h1").First().Text()p := doc.Find("p").First().Text()type Example struct {&nbsp; &nbsp; foo string&nbsp; &nbsp; bar string}e := Example{ foo: h1, bar: p }
随时随地看视频慕课网APP

相关分类

Go
我要回答