【问题标题】:Getting hrefs under <li> from <ul> using Cheerio使用 Cheerio 从 <ul> 获取 <li> 下的 href
【发布时间】:2019-03-25 07:16:01
【问题描述】:

这可能不是有史以来最好的问题,但我真的无法解决这个问题。

我要做的是从下面的 html 中获取 href。

<ul id="nav-products">
  <li><a class="" href="/shop/hats/">yellow good looking hat</a></li>
  <li><a class="" href="/shop/shoes/">cat feet holders</a></li>
</ul>

这个,来自使用 Cheerio 的 Node.js。

const fs = require("fs");
const cheerio = require("cheerio")
const html = fs.readFileSync('text.html', "utf8")

const $ = cheerio.load(html);



$('#nav-products').each((i, el) => {
    const category = $(el).text();
    const children = $(el).children();


    console.log(children.attr('href'));
    console.log(category);
});

但是,我尝试了多种方法,但都没有奏效。例如:

const link = $(el).attr('href');

link/children.attr('href') 常量仍未定义。 谢谢。

【问题讨论】:

  • 您也可以.find(...) 查找锚点,因为@Marcus 建议使用他们的hrefs

标签: javascript node.js cheerio


【解决方案1】:

在您的代码 sn-p 中,children 包含无序列表的列表项,但 href 属性定义在锚元素上,而锚元素又是其列表项父项的子项。因此,您需要迭代 children 并让每个孩子的孩子获得锚项目。

$('#nav-products').each((i, ul) => {
  const children = $(ul).children();
  children.each((i, li) => {
    const children = $(li).children();
    children.each((i, a) => {
      console.log($(a).attr('href'));
      console.log($(a).text())
    })
  })
});

编辑:这是@82Tuskers 建议的使用find() 的示例

$('#nav-products').each((i, ul) => {
  const children = $(ul).children();
  const selectedAnchors = $(ul).find("A");
  selectedAnchors.each((i, a) => {
    console.log($(a).attr('href'));
    console.log($(a).text())
  })
});

我的建议是通过使用一个选择器来简化此操作,该选择器将#nav-products 列表的列表项的锚元素的范围如下:

$('#nav-products LI A').each((i, el) => {
  console.log($(el).text());
  console.log($(el).attr('href'));
});

你可以在repl.it上尝试所有的sn-ps

【讨论】:

    【解决方案2】:

    确保您正在迭代 a 的:

    let links = $('a').map((i, a) => {
      return {
        text: $(a).text(),
        href: $(a).attr('href')
      }
    }).get()
    

    如果你打算对数据做一些有用的事情,通常你需要map而不是each

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2022-12-05
      • 2016-09-22
      • 1970-01-01
      相关资源
      最近更新 更多