13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでrequestを使ってeuc-jpのサイトをスクレイピング時に注意する事

Posted at

node.jsでeuc-jpのサイトをスクレイピングしようとしたらハマった。
文字コードを指定して変換したつもりだけど、文字化けしまくってた。

ダメな例

var request = require('request');
var Iconv = require('iconv').Iconv;
var fs = require('fs');
request('http://hoge.jp', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var iconv = new Iconv('EUC-JP', 'UTF-8//TRANSLIT//IGNORE');
    body = iconv.convert(body).toString();
    fs.writeFile('hoge.txt', body);
  }
});

良い例

var request = require('request');
var Iconv = require('iconv').Iconv;
var fs = require('fs');
request({url: 'http://hoge.jp', encoding: null }, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var iconv = new Iconv('EUC-JP', 'UTF-8//TRANSLIT//IGNORE');
    body = iconv.convert(body).toString();
    fs.writeFile('hoge.txt', body);
  }
});

文字コードを明確にnullを指定しないと、requestのモジュール内で勝手にbody.toString()とよしなに変換してくれようとするのです!

この辺。

ってか、参考サイトそのままコピペしたようなコードになっておる。。。

地味にハマりました。。。(泣)

thanks

13
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?