javascript - 获取下的hrefs
- 使用 Cheerio
问题描述
这可能不是有史以来最好的问题,但我真的无法让它发挥作用。
我想要做的是从下面的 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')
常量仍然是未定义的。谢谢。
解决方案
在您的代码片段中,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上尝试所有片段
推荐阅读
- numpy - 访问张量中索引处的元素
- java - java 8顺序流有直接或间接的性能优势吗?
- javascript - Java 行 websocket 数据传输
- android - 如何从颤动中打开具有布局的特定android Activity
- fortran - 如何使用编辑器运行 fortran 子例程
- javascript - 单元测试错误:无法读取未定义的属性“地图”
- firebase - Firebase 索引在幕后有什么作用?
- jdbc - 我们可以在 Windows 操作系统中运行 Confluent JDBC Kafka 连接器吗?
- java - Android,JaCoco 无法为“android.uid.system”创建覆盖
- java - 在没有库的情况下在 Java 中读取 PKCS#1 或 SPKI 公钥