【发布时间】:2014-01-13 20:02:18
【问题描述】:
我想用 NodeJS 和 Cheerio 库抓取 Google 翻译:
request("http://translate.google.de/#de/en/hallo%20welt", function(err, resp, body) {
if(err) throw err;
$ = cheerio.load(body);
console.log($('#result_box').find('span').length);
}
但他无法从翻译框 (result_box) 中找到必要的跨度元素。在网站的源代码中是这样的:
<span id="result_box">
<span class="hps">hello</span>
<span class="hps">world</span>
</span>
所以我想我可以等待 5 到 10 秒,直到 Google 创建了所有跨度元素,但不......似乎不是......
setTimeout(function() {
$ = cheerio.load(body);
console.log($('#result_box').find('span').length);
}, 15000);
你能帮帮我吗? :)
解决方案:
我使用 http.get 而不是cheerio:
http.get(
this.prepareURL("http://translate.google.de/translate_a/t?client=t&sl=de&tl=en&hl=de&ie=UTF-8&oe=UTF-8&oc=2&otf=1&ssel=5&tsel=5&pc=1&q=Hallo",
function(result) {
result.setEncoding('utf8');
result.on("data", function(chunk) {
console.log(chunk);
});
}));
所以我得到一个带有翻译的结果字符串。使用的 url 是对服务器的请求。
【问题讨论】:
-
你为什么不使用developers.google.com/translate ?查看此页面:stackoverflow.com/questions/14339190/… 以获取更多参考资料
-
@leobelizquierdo 如果有一天我不得不再次抓取谷歌翻译,我最终会使用它。但到目前为止,这是一个我很满意的免费解决方案。 ;)
标签: node.js web-scraping cheerio