登录
首页 >  Golang >  Go问答

colly:invalid memory address or nil pointer dereference

来源:SegmentFault

时间:2023-01-11 09:33:01 176浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《colly:invalid memory address or nil pointer dereference》,介绍一下go、网页爬虫,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

今天用colly写了个demo,下面是代码

func downloadImages(e *colly.HTMLElement) {
    srcRef := destUrl + e.Attr("src")
    res, _ := http.Get(srcRef)
    if strings.Contains(srcRef, "http") && strings.Contains(srcRef, ".jpg") {
        arr := strings.Split(srcRef, "/")
        fileName := strings.Split(arr[len(arr)-1], ".")[0]
        fmt.Println("fileName", fileName)
        f, _ := os.Create("./images/" + fileName + ".jpg")
        defer f.Close()
        written, _ := io.Copy(f, res.Body)

        fmt.Println("info", written)
    }
}

下面是出错信息:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x48 pc=0x868eeb]

goroutine 1 [running]:
main.downloadImages(0xc000256240)
 C:/Users/DELL/Desktop/work/golang/colly/colly.go:28 +0x32b
main.main.func1(0xc000256240)
 C:/Users/DELL/Desktop/work/golang/colly/colly.go:39 +0x32
github.com/gocolly/colly.(\*Collector).handleOnHTML.func1(0x6, 0xc000248390)
 C:/Users/DELL/go/pkg/mod/github.com/gocolly/colly@v1.2.0/colly.go:963 +0x93
github.com/PuerkitoBio/goquery.(\*Selection).Each(0xc00020bb00, 0xc000099cb0, 0x6)
 C:/Users/DELL/go/pkg/mod/github.com/!puerkito!bio/goquery@v1.6.0/iteration.go:10 +0x5a
github.com/gocolly/colly.(\*Collector).handleOnHTML(0xc00006b860, 0xc0001620c0, 0x0, 0x0)
 C:/Users/DELL/go/pkg/mod/github.com/gocolly/colly@v1.2.0/colly.go:953 +0x222
github.com/gocolly/colly.(\*Collector).fetch(0xc00006b860, 0xc00001ed40, 0x14, 0x9792e0, 0x3, 0x1, 0x0, 0x0, 0xc000055fb0, 0xc00012cb70, ...)
 C:/Users/DELL/go/pkg/mod/github.com/gocolly/colly@v1.2.0/colly.go:623 +0x44d
github.com/gocolly/colly.(\*Collector).scrape(0xc00006b860, 0xc00001ed40, 0x14, 0x9792e0, 0x3, 0x1, 0x0, 0x0, 0x0, 0xc00012cb70, ...)
 C:/Users/DELL/go/pkg/mod/github.com/gocolly/colly@v1.2.0/colly.go:535 +0x46b
github.com/gocolly/colly.(\*Collector).Visit(0xc00006b860, 0x98544c, 0x14, 0x9a3198, 0x8b2a00)
 C:/Users/DELL/go/pkg/mod/github.com/gocolly/colly@v1.2.0/colly.go:412 +0x89
main.main()
 C:/Users/DELL/Desktop/work/golang/colly/colly.go:55 +0xd7
exit status 2

请教大佬哪里出错了.

正确答案

colly.go
第55行出现了空指针引用

今天关于《colly:invalid memory address or nil pointer dereference》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>