一般情况下(utf-8编码)的go爬虫(1)

本文介绍了一种使用Go语言进行网页爬虫的方法,包括通过http.Get获取网页资源,检查HTTP状态码,判断网页编码并进行解码。示例代码展示了如何使用bufio和charset库来确定及转换网页的编码方式,从而正确读取和打印UTF-8编码的网页内容。
摘要由CSDN通过智能技术生成

一般情况下的go爬虫

省略导包

utf-8编码的网页爬虫为例

1.get:向服务器请求资源地址,返回http页面的响应

2.判断response的type,若为200即可

3.通过ioutil.ReadAll()读取response Body

func main(){
	resp,err:=http.Get("https://www.qidian.com/")
	if err!=nil{
		panic(err)
	}
	defer resp.Body.Close()
	resp.StatusCode=100
	if resp.StatusCode!=http.StatusOK{
		fmt.Printf("Error status code:%d",resp.StatusCode)
	}
	result,err:=ioutil.ReadAll(resp.Body)
	if err!=nil{
		panic(err)
	}
	fmt.Printf("%s",result)
}

http包下的get获取特定url下的资源

func Get(url string) (resp *Response, err error) {
	return DefaultClient.Get(url)
}

若无响应则返回不为空的err.

判断网页编码方式在进行爬虫

首先通过一函数判断特定url网页的编码方式是utf-8或gbk等,再以此进行特定的爬虫

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
}
func main(){
	resp,err:=http.Get("https://www.qidian.com/")
	if err!=nil{
		panic(err)
	}
	defer resp.Body.Close()
	resp.StatusCode=100
	if resp.StatusCode!=http.StatusOK{
		fmt.Printf("Error status code:%d",resp.StatusCode)
	}
    bodyReader:=bufio.NewReader(resp.Body)//创建一个副本
    e:=determinEncoding(bodyReader)//判断编码方式
    utf8Reader:=transform.NewReader(bodyReader,e.newDecoder())//转换为对应编码方式
	result,err:=ioutil.ReadAll(utf8Reader)//解码获取页面html代码
	if err!=nil{
		panic(err)
	}
	fmt.Printf("%s",result)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值