【发布时间】: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