【Go语言实战】Go语言写爬虫:working directory is not part of a module

在使用Go语言编写爬虫时遇到编码问题,当遇到非UTF8编码的网页时,会出现乱码。为解决此问题,创建了一个determinEncoding函数来探测网页的编码方式。然而,在引入golang.org/x/net/html/charset等包时,由于Go模块问题导致编译错误。通常的解决办法是在项目根目录下执行`go mod init`初始化模块,但执行后依然报错,提示当前工作目录不是模块的一部分。这可能是因为直接通过git clone方式下载了依赖包,而非通过go mod下载,导致依赖路径不正确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Go语言写爬虫:working directory is not part of a module

问题描述:

在使用Go语言获取网页信息时,默认解析为UTF8格式,如果出现GB2312的编码格式,则出现乱码,因此,使用创建探测函数确定网页编码方式。函数如下:

func determinEncoding(r *bufio.Reader) encoding.Encoding {
	bytes, err := r.Peek(1024)
	if err != nil {
		log.Printf("fetch error : %v", err)
		return unicode.UTF8
	}
	e, _, _ := charset.DetermineEncoding(bytes, "")
	return e
}

在这个过程中需要依赖text、net等包,由于golang.org包的下载问题,这里采用直接git clone的方式下载到$GOPATH的src目录下,代码如下:

PANG@LAPTOP-PCSTF4VE MINGW64 /d/Go_WorkSpaces/go/src
$ git clone https://github.com/golang/text.git ./golang.org/x/text
$ git clone https://github.com/golang/net.git ./golang.org/x/net

但是在编译执行的时候出现如下错误:

main.go:6:2: cannot find module providing package golang.org/x/net/html/charset: working directory is not part of a module
main.go:7:2: cannot find module providing package golang.org/x/text/encoding: working directory is not part of a module
main.go:8:2: cannot find module providing package golang.org/x/text/encoding/unicode: working directory is not part of a module
main.go:9:2: cannot find module providing package golang.org/x/text/transform: working directory is not part of a module

问题分析:

一般网上的资料都是建议在工程的根目录下执行go mod init projectName命令在执行go mod化之后,所有的引用都不再是以GOPATH为相对路径的引用了,而是变成了以go.mod中初始化的项目名为起始的引用。

PANG@LAPTOP-PCSTF4VE MINGW64 /d/Go_WorkSpaces/crawl
$ go mod init crawl
go: creating new go.mod: module crawl
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

镰刀韭菜

看在我不断努力的份上,支持我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值