扫码关注官方订阅号
用nodejs在未知网站编码的时候 爬取网站内容 如何才能不中文乱码。
在已知网站的编码的情况下,我已经知道如何处理了。未知网站编码的情况下海不知道了,求大大赐教
光阴似箭催人老,日月如移越少年。
可以先从网页的meta里判断一下charset,然后再用iconv转
javascriptrequire("request").get({ url : url ,encoding : null} ,function(err, response, body){ var charset="utf-8"; var arr=body.toString().match(/<meta([^>]*?)>/g); if(arr){ arr.forEach(function(val){ var match=val.match(/charset\s*=\s*(.+)\"/); if(match && match[1]){ if(match[1].substr(0,1)=='"')match[1]=match[1].substr(1); charset=match[1].trim(); return false; } }) } var data = require('iconv-lite').decode(body, charset); // console.log(data); })
javascript
require("request").get({ url : url ,encoding : null} ,function(err, response, body){ var charset="utf-8"; var arr=body.toString().match(/<meta([^>]*?)>/g); if(arr){ arr.forEach(function(val){ var match=val.match(/charset\s*=\s*(.+)\"/); if(match && match[1]){ if(match[1].substr(0,1)=='"')match[1]=match[1].substr(1); charset=match[1].trim(); return false; } }) } var data = require('iconv-lite').decode(body, charset); // console.log(data); })
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
可以先从网页的meta里判断一下charset,然后再用iconv转