我想用 NodeJS 和 Cheerio 库来抓取谷歌翻译:
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 秒,直到谷歌创建了所有跨度元素,但没有.. 似乎不是..
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 是对服务器的请求。