首页 > 解决方案 > 获取下的hrefs

  • 问题描述

    这可能不是有史以来最好的问题,但我真的无法让它发挥作用。

    我想要做的是从下面的 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')常量仍然是未定义的。谢谢。

    标签: javascriptnode.jscheerio

    解决方案


    在您的代码片段中,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())
        })
      })
    });
    

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

    $('#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上尝试所有片段


    推荐阅读