Node.js爬虫抓取日文内容出现乱码问题求助
解决Node.js爬虫抓取日文论坛的乱码问题
你用node-fetch抓取日文论坛内容时出现乱码,哪怕设置了UTF-8请求头也没用,核心原因是多数日文网站用Shift_JIS(或EUC-JP、ISO-2022-JP)编码,而node-fetch默认用UTF-8解析,导致编码不匹配。下面是几个可行的解决办法:
方案1:手动指定编码解码二进制数据
先安装编码处理依赖:
npm install iconv-lite
修改代码,先获取原始二进制数据,再用对应编码解码:
import fetch from 'node-fetch'; import { JSDOM } from 'jsdom'; import iconv from 'iconv-lite'; fetch('https://target-website.tld/bbs.cgi') .then(response => response.buffer()) // 获取二进制缓冲区 .then(buffer => { // 日文网站优先试Shift_JIS编码,不行换EUC-JP或ISO-2022-JP const htmlString = iconv.decode(buffer, 'Shift_JIS'); const dom = new JSDOM(htmlString); const blockQuotes = dom.window.document.querySelectorAll('blockquote'); blockQuotes.forEach(blockQuote => { const preElements = blockQuote.querySelectorAll('pre'); preElements.forEach(pre => { console.log(pre.textContent.trim()); }); }); }) .catch(error => console.error('Error fetching HTML:', error));
方案2:自动从响应头提取编码(更稳妥)
有些网站会在Content-Type响应头里明确标注编码,比如text/html; charset=Shift_JIS,可以自动提取后解码:
import fetch from 'node-fetch'; import { JSDOM } from 'jsdom'; import iconv from 'iconv-lite'; fetch('https://target-website.tld/bbs.cgi') .then(response => { // 从响应头解析编码,解析失败默认用Shift_JIS const contentType = response.headers.get('Content-Type'); const charset = contentType?.match(/charset=([^;]+)/)?.[1] || 'Shift_JIS'; return response.buffer().then(buffer => iconv.decode(buffer, charset)); }) .then(htmlString => { const dom = new JSDOM(htmlString); const blockQuotes = dom.window.document.querySelectorAll('blockquote'); blockQuotes.forEach(blockQuote => { const preElements = blockQuote.querySelectorAll('pre'); preElements.forEach(pre => { console.log(pre.textContent.trim()); }); }); }) .catch(error => console.error('Error fetching HTML:', error));
方案3:给JSDOM明确指定编码
如果解码后JSDOM仍有乱码,可以在创建实例时指定内容类型编码:
const dom = new JSDOM(htmlString, { contentType: `text/html; charset=${charset}` // 传入实际使用的编码 });
日文论坛90%以上用Shift_JIS编码,先试方案1基本能解决问题。
内容的提问来源于stack exchange,提问作者もぐもぐぷりん
相关产品推荐
相关产品推荐

