Colly 报错“invalid memory address or nil pointer dereference”,如何解决?

colly 报错“invalid memory address or nil pointer dereference”,如何解决?

colly 报错:“invalid memory address or nil pointer dereference”

原代码摘自问题描述:

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)
    }
}

代码在第55行执行 os.create 操作时发生空指针引用错误。这是因为在对 srcref 进行拆分操作时,没有检查 srcref 是否为 nil,或者对应的文件和目录是否存在。

修改后的代码如下:

func downloadImages(e *colly.HTMLElement) {
    srcRef := destUrl + e.Attr("src")
    if srcRef == "" {
        return
    }

    res, err := http.Get(srcRef)
    if err != nil {
        log.Printf("Failed to fetch image: %v", err)
        return
    }

    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)

        path := "./images/" + fileName + ".jpg"
        f, err := os.Create(path)
        if err != nil {
            log.Printf("Failed to create file: %v", err)
            return
        }
        defer f.Close()

        written, err := io.Copy(f, res.Body)
        if err != nil {
            log.Printf("Failed to write to file: %v", err)
            return
        }

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

以上就是Colly 报错“invalid memory address or nil pointer dereference”,如何解决?的详细内容,更多请关注其它相关文章!