Node.js Crawl utf-8 Chinese web page will appear garbled problem, such as the first page of NetEase code is gb2312, crawl will appear garbled
Copy Code code 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
Installation
Copy Code code as follows:
At the same time we have to modify the user-agent to prevent the site screen:
Copy Code code 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/537.36 '
}
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
Parsing HTML using Cheerio
Cheerio can be easily understood as a server-side JQuery selector, and with it, a lot more intuitive than regular
Installation
Copy Code code 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 ())
Console.log ($ (' H1 '). HTML ())
})
Output is as follows
Copy Code code as follows:
So here's the question, $ (' H1 '). The HTML () output code is UNICODE encoded, NetEase has become netease, to our character processing brought some trouble
Solve Cheerio. HTML () "garbled" problem
consult a document to see that you can turn off the functionality of this transform entity encoding
Copy Code code as follows:
var $ = cheerio.load (HTML)
Change into
Copy Code code as follows:
var $ = cheerio.load (HTML, {decodeentities:false})
The complete code is as follows:
Copy Code code as follows:
var originrequest = require (' request ')
var cheerio = require (' Che Erio ')
var iconv = require (' iconv-lite ')
var headers = {
' user-agent ': ' Mozi lla/5.0 (Macintosh; Intel Mac OS X 10_10_1) applewebkit/537.36 (khtml, like Gecko) chrome/39.0.2171.65 safari/537.36 '
}
Fu Nction 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 ())
Console.log ($ (' H1 '). html ())
)