Golang网页爬虫代码报错问题排查
Golang网页爬虫代码报错问题排查 你好,GoLang 世界!
这是我的第一个帖子。{(我相信以后还会有更多 :))}
我按照一个视频教程输入了我的代码,但到目前为止遇到了两个错误,不知道如何或需要什么来解决这两个错误。
我在 Windows 10 上使用 Visual Studio Code。
-
.\main.go:25:4: undefined: log collector.OnHTML(".factList li", func(element *colly.HTMLElement){ factID, err := strconv.Atoi(element.Attr(“id”)) if err != nil { log.Println(“Could not get id”)
-
.\main.go:31:8: undefined: factId factDesc := element.Text
fact := Fact{ ID: factId, Description: factDesc, }
以下是完整的代码行:
package main
import (
"github.com/gocolly/colly"
"strconv"
"fmt"
)
type Fact struct {
ID int `json:"id"`
Description string `json:"description"`
}
func main() {
allFacts := make([]Fact, 0)
collector := colly.NewCollector(
colly.AllowedDomains("factretriever.com", "www.factretreiver.com"),
)
collector.OnHTML(".factList li", func(element *colly.HTMLElement){
factID, err := strconv.Atoi(element.Attr("id"))
if err != nil {
log.Println("Could not get id")
}
factDesc := element.Text
fact := Fact{
ID: factId,
Description: factDesc,
}
allFacts = append(allFacts, fact)
})
collector.OnRequest(func(request *colly.Request) {
fmt.Println("Visiting: ", request.URL.String())
})
collector.Visit("https://www.factretriever.com/rhino-facts")
}
更多关于Golang网页爬虫代码报错问题排查的实战教程也可以访问 https://www.itying.com/category-94-b0.html
你好, 对于错误1,看起来你忘记导入log包了,所以应该是:
import (
"github.com/gocolly/colly"
"strconv"
"fmt"
"log"
)
对于错误2,有一个小的拼写错误,因为你声明了:
factID, err := strconv.Atoi(element.Attr("id"))
但后面却使用了:
fact := Fact{
ID: factId,
Description: factDesc,
}
所以应该是 factID 而不是 factId
更多关于Golang网页爬虫代码报错问题排查的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
第一个错误是因为没有导入 log 包。在代码开头添加 "log" 到导入列表即可解决。
第二个错误是变量名大小写不一致导致的。Go语言中变量名区分大小写,factID 和 factId 被视为两个不同的变量。
以下是修正后的代码:
package main
import (
"fmt"
"log"
"strconv"
"github.com/gocolly/colly"
)
type Fact struct {
ID int `json:"id"`
Description string `json:"description"`
}
func main() {
allFacts := make([]Fact, 0)
collector := colly.NewCollector(
colly.AllowedDomains("factretriever.com", "www.factretriever.com"),
)
collector.OnHTML(".factList li", func(element *colly.HTMLElement) {
factID, err := strconv.Atoi(element.Attr("id"))
if err != nil {
log.Println("Could not get id")
}
factDesc := element.Text
fact := Fact{
ID: factID, // 这里使用 factID 而不是 factId
Description: factDesc,
}
allFacts = append(allFacts, fact)
})
collector.OnRequest(func(request *colly.Request) {
fmt.Println("Visiting: ", request.URL.String())
})
collector.Visit("https://www.factretriever.com/rhino-facts")
}
主要修改:
- 添加了
"log"包的导入 - 将
factId改为factID(保持变量名一致) - 修正了域名拼写错误:
"www.factretreiver.com"改为"www.factretriever.com"
注意:代码中 element.Attr("id") 获取的是字符串属性,需要确保HTML元素确实有id属性且为数字格式,否则 strconv.Atoi() 会返回错误。

