简短版本 Jquery: $('img')[0]
不等于 Cheerio: $('img')[0]
为什么?
我的目标是获取查询的第一个图像网址
我读到,cheerio 是解析 html 数据的好方法,就像使用 jquery 一样。也许我错了,还有其他更好的东西吗?
我将 jquery 加载到控制台并访问 https://www.google.com/search?tbm=isch&q=duck设置我的cheerio 命令。
$('div img')[2].parentNode.href
返回
I cant post more than two links, but it returns the correct link
好的,现在我加载 Node 终端并输入以下命令。
request('https://www.google.com/search?tbm=isch&q=duck', function(e,r,d){
console.log(cheerio.load(d)('div img')[2].parentNode.href)
})
返回
undefined
由于某种原因
request('https://www.google.com/search?tbm=isch&q=duck', function(e,r,d){
console.log(cheerio.load(d)('div img')[2].parentNode.attribs.href)
})
返回
这很接近,但与我第一次在 Chrome 控制台上得到的网址不同?这是怎么回事?如何从 Node 获取与我在 chrome 控制台上获取的相同字符串?
最佳答案
回答您的简短版本:request() 访问的html 与控制台中jQuery 访问的html 不同。
请求获取静态 html,而在浏览器中,一旦加载脚本标签或 .js 文件,JavaScript 就可以修改 html。任何此类更改都不会出现在通过请求访问的 html 中。以您的代码为例,尝试运行类似的内容
request('https://www.google.com/search?tbm=isch&q=duck', function(e,r,d){
console.log(d);
});
并将输出保存为 html 文件。将此 html 与浏览器 html 进行比较。他们是不同的。特别注意,图像和 anchor 标记的属性两者之间是不同的。
将此逻辑应用到您的示例中,我最好的猜测是 Google(出于目前对我而言不明显的原因)运行 JavaScript 来更改 anchor 标记中 href 的值。
关于jquery - 为什么 Cheerio 不像 jquery 那样工作(不同的结果),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44820307/