gpt4 book ai didi

go - 如何在 Go 中获取 DOM HTML

转载 作者:数据小太阳 更新时间:2023-10-29 03:19:49 25 4
gpt4 key购买 nike

我正在用 Go 编写解析器 HTML。我需要获取 HTML 并将其传递给另一个函数。

我是这样做的:

  1. 不能将“doc”传递给另一个函数
receivedURL, err := http.Get("http://lavillitacafe.com/")
doc, err := goquery.NewDocumentFromReader(receivedURL.Body)
//"linkScrape" this is another function
contactURL := linkScrape(doc)

  1. HTML 被部分地转移到另一个函数。
resp, err := http.Get("http://lavillitacafe.com/")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
for true {

bs := make([]byte, 1014)
n, err := resp.Body.Read(bs)
contactURL := linkScrape(bs[:n])
if n == 0 || err != nil{
break
}
}

我该怎么做才正确?

最佳答案

这是根据您的用例调整的基本 goquery 示例:

package main

import (
"fmt"
"log"
"strings"

"github.com/PuerkitoBio/goquery"
)

func findHeader(d *goquery.Document) string {
header := d.Find("h1").Text()
return header
}

func main() {
// create from a string
data := `
<html>
<head>
<title>My document</title>
</head>
<body>
<h1>Header</h1>
</body>
</html>`

doc, err := goquery.NewDocumentFromReader(strings.NewReader(data))
if err != nil {
log.Fatal(err)
}

fmt.Println(findHeader(doc))
}

关于go - 如何在 Go 中获取 DOM HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55792071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com