之前在用 node 做爬虫时碰到的中文乱码问题一直没有解决,今天整理下备忘。(PS:网上一些解决方案都已经不行了)
中文乱码具体是指用 node 请求 gbk 编码的网页,无法正确获取网页中的中文(需要转码),"gbk" 和 "网页中的中文" 两个条件是缺一不可的。可以获取 utf-8 编码的网页中的中文,也可以获取 gbk 编码网页中的英文数字等。
举个简单的例子。获取 http://acm.hdu.edu.cn/statistic.php?pid=1000排名第一的答案的 username,是为 "极光炫影"。刷刷刷写下如下代码:
var cheerio = require('cheerio') , superagent = require('superagent') , express = require('express');var url = 'http://acm.hdu.edu.cn/statistic.php?pid=1000';var app = express();app.get('/', function (req, res, next) { superagent.get(url) .end(function (err, sres) { var html = sres.text; var $ = cheerio.load(html, {decodeEntities: false}); var ans = $('.table_text td a').eq(0).html(); res.send(ans); }); });app.listen(3000, function () { console.log('app is listening at port 3000');});
得到了乱码,如下:
������Ӱ
如何获取正确的中文呢?这里提供几个解决方案应急(不关心原理,只是为了应急)。
方法一:
使用 superagent-charset模块。
var cheerio = require('cheerio') , superagent = require('superagent-charset') , express = require('express');var url = 'http://acm.hdu.edu.cn/statistic.php?pid=1000';var app = express();app.get('/', function (req, res, next) { superagent.get(url) .charset('gbk') .end(function (err, sres) { var html = sres.text; var $ = cheerio.load(html, {decodeEntities: false}); var ans = $('.table_text td a').eq(0).html(); res.send(ans); });});app.listen(3000, function () { console.log('app is listening at port 3000');});
使用非常简单,只需要引入 superagent-charset模块,且在链式调用时加入 charset 参数即可。superagent-charset 模块包括了 superAgent 模块以及 iconv-lite 模块。源码可以参考 Github。
方法二:
直接用 iconv-lite模块进行转码。
iconv-lite是一个进行编码转换的模块(node 默认编码 utf-8)。需要 decode 的编码必须是 Buffer类型。
-
用 http模块:
http.get(url, function(sres) { var chunks = []; sres.on('data', function(chunk) { chunks.push(chunk); }); sres.on('end', function() { // 将二进制数据解码成 gb2312 编码数据 var html = iconv.decode(Buffer.concat(chunks), 'gb2312'); var $ = cheerio.load(html, {decodeEntities: false}); var ans = $('.table_text td a').eq(0).html(); res.send(ans); });});
-
用 request模块:
request({ url: url, encoding: null // 关键代码}, function (err, sres, body) { var html = iconv.decode(body, 'gb2312') var $ = cheerio.load(html, {decodeEntities: false}); var ans = $('.table_text td a').eq(0).html(); res.send(ans);});
用 iconv 进行 decode 传入的参数必须是 Buffer。
encoding- Encoding to be used on setEncoding of responsedata. If null, the bodyis returned as a Buffer. Anything else ( including the default value of undefined ) will be passed as the encoding parameter to toString()(meaning this is effectively utf8by default). ( Note: if you expect binary data, you should set encoding: null.)
iconv-lite 模块能配合 http 模块以及 request 模块使用,却不能直接和 superAgent 模块使用。 因为 superAgent 是以 utf8 去取数据,然后再用 iconv 转也是不行的。页面是 gbk 编码的,sres.text 已经是 decode 过了的结果,也就是说它已经被转换成 utf8 了,再转换成 buffer 出来的结果必须是不正确的。

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software