我想用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);你能帮帮我吗?)
解决方案:
我使用的不是cheerio,而是http.get:
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是对服务器的请求。
发布于 2018-05-14 12:46:33
我知道您已经解决了这个问题,但是我认为您的代码不能工作的原因是您应该编写....find(“span.hps”).
或者至少对我来说,它总是只在类标识符存在的时候起作用。
发布于 2018-12-29 18:29:12
您不能在节点中使用cheerio搜索google翻译的原因是,google没有在google侧呈现翻译页面!他们用脚本回复您的请求,然后脚本发出包含您的字符串的api请求。然后,用户端的脚本再次运行,并构建您所看到的内容,这就是在cheerio中没有发生的事情!
所以你需要对api做一个请求,但它是谷歌,他们可以检测到刮擦,所以他们会阻止你在几次尝试!
你仍然可以伪造一个用户的行为,但这将花费很长的时间,他们可能会在任何时候阻止你!
https://stackoverflow.com/questions/21100321
复制相似问题