抓取这个网页http://www.runoob.com/nodejs/...出现乱码,网页编码为utf-8,用过iconv-lite还是不行,这是为什么?
var http=require("http");
var go=require("iconv-lite")
http.get("http://www.runoob.com/nodejs/nodejs-tutorial.html",function(res){
var html="";
res.on("data",function(data){
/* html +=go.decode(data,"gb2312");*/
html+=data;
})
res.on("end",function(){
console.log(html);
}).on("error",function(){
console.log("获取失败")
})
})
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这个不是编码的问题,编码确实是
utf-8,但是这个网页使用gzip进行了压缩,所以请求之后需要先进行ungzip。推荐使用
request,可以比较方便的解决这个问题,只需要添加一个参数:补充一下不用第三方包的写法:
数据是gzip压缩后的数据,所以建议不要直接使用字符串拼接,而是采用Buffer的concat方法。之后使用自带的zlib进行
gunzip即可。这个写法只是针对这一个问题而已,实际应用中需要自己去判断返回内容的encoding。当然了,第三方的工具,比如request和楼下的superAgent会更加方便一些。
发送header头
superAgent表示毫无压力 ...因为这个网页的内容是 gzip 压缩的,接收数据后需要解压缩方能正确显示网页内容。