【问题标题】:cheerio jquery node js: obtaining href valueCheerio jquery node js:获取href值
【发布时间】:2018-07-18 00:00:50
【问题描述】:

Source

想要href 值,所以在这种情况下:链接。

希望所有遵循相同模式的值都在 .product-name 类中。

尝试返回空白/无的方法。

回答后,请简要介绍一下cheerio/jquery的一些规则,因为我不明白。

仅供参考:const $ = cheerio.load(response) //page source.

【问题讨论】:

  • 有人在解答吗?
  • 你尝试了什么来获取这些元素的href?
  • console.log($('.product-name').attr('a[href]').text())
  • BUMPPP不会更快得到答案,其实很烦人,会适得其反。

标签: jquery node.js cheerio


【解决方案1】:

试试这个:

$('.product-name a[href]').each((index, elem)=>{
    console.log(index, $(elem).attr('href'));
});
/** .product-name : choose class .product-name
 *  .product-name a : choose tag a is child of class product-name
 *  and a[href] : choose tag a has attribute href, if you don't need, you can remove it.
 **/

对于第一个链接:

let firstElem = $('.product-name a[href]').get()[0]
console.log($(firstElem).attr('href'));

【讨论】:

  • 如何调用第一个链接?
  • 您可以添加条件index == 0(或使用我编辑的答案中的方法)
  • 哦,好的,谢谢,您能解释一下为什么将 attr [href] 添加到 '.product-name a[href]' 中,然后再为 .attr('href')) 添加/跨度>
  • .attr('href') : 获取元素的属性href
  • 是的好吧,但是你为什么写在class之后.product-name
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2021-02-26
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多