This article mainly introduces Node. this article describes how to use some open-source libraries to solve the garbled problem during crawling. For more information, see Node. garbled characters may occur when JavaScript captures a non-UTF-8 Chinese webpage. for example, if NetEase's homepage code is gb2312, garbled characters may occur during crawling.
The code is as follows:
Var request = require ('request ')
Var url = 'http: // www.163.com'
Request (url, function (err, res, body ){
Console. log (body)
})
You can use iconv-lite to solve this problem.
Install
The code is as follows:
Npm install iconv-lite
At the same time, we can modify the user-agent to prevent website blocking:
The code is as follows:
Var originRequest = require ('request ')
Var iconv = require ('iconv-lite ')
Var headers = {
'User-Agent': 'mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/8080'
}
Function request (url, callback ){
Var options = {
Url: url,
Encoding: null,
Headers: headers
}
OriginRequest (options, callback)
}
Request (url, function (err, res, body ){
Var html = iconv. decode (body, 'gb2312 ')
Console. log (html)
})
Garbled problem solving
Use cheerio to parse HTML
Cheerio can be simply and roughly understood as the jQuery selector on the server side. it is much more intuitive than regular expressions.
Install
The code is as follows:
Npm install cheerio
Request (url, function (err, res, body ){
Var html = iconv. decode (body, 'gb2312 ')
Var $ = cheerio. load (html)
Console. log ($ ('h1 '). text ())
Lele.log((('h1'{.html ())
})
Output:
The code is as follows:
NetEase
NetEase
As a matter of question, the code output by ('h1'{.html () is Unicode encoded, and NetEase has become NetEase, which brings us some trouble in character processing.
Solve the "garbled" problem of cheerio. html ()
You can disable this function to convert entity encoding.
The code is as follows:
Var $ = cheerio. load (html)
Change
The code is as follows:
Var $ = cheerio. load (html, {decodeEntities: false })
The complete code is as follows:
The code is as follows:
Var originRequest = require ('request ')
Var cheerio = require ('Cheerio ')
Var iconv = require ('iconv-lite ')
Var headers = {
'User-Agent': 'mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/8080'
}
Function request (url, callback ){
Var options = {
Url: url,
Encoding: null,
Headers: headers
}
OriginRequest (options, callback)
}
Var url = 'http: // www.163.com'
Request (url, function (err, res, body ){
Var html = iconv. decode (body, 'gb2312 ')
Var $ = cheerio. load (html, {decodeEntities: false })
Console. log ($ ('h1 '). text ())
Lele.log((('h1'{.html ())
})