cheerio / jquery 选择器:如何获取标签 a 中的文本?
cheerio / jquery selectors: how to get text in tag a?
我正在尝试访问网站上的链接。该网站看起来像第一个代码示例,链接位于不同的 div-containers:
<div id="list">
<div class="class1">
<div class="item-class1">
<a href="http://www.example.com/1">example1</a>
</div>
</div>
<div class="class2">
<div class="item-class2">
<a href="http://www.example.com/2">example2</a>
</div>
</div>
</div>
我确实尝试使用以下代码提取链接:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).attr('href'));
});
但是输出看起来像这样:
0: "http://www.example.com/1"
1: "http://www.example.com/2"
但我希望它看起来像这样:
0: example1
1: example2
非常感谢。
$(element).attr('href')
==> 获取 href 属性 : link
$(element).text()
==> 获取文本
改成这样:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).text());
});
我正在尝试访问网站上的链接。该网站看起来像第一个代码示例,链接位于不同的 div-containers:
<div id="list">
<div class="class1">
<div class="item-class1">
<a href="http://www.example.com/1">example1</a>
</div>
</div>
<div class="class2">
<div class="item-class2">
<a href="http://www.example.com/2">example2</a>
</div>
</div>
</div>
我确实尝试使用以下代码提取链接:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).attr('href'));
});
但是输出看起来像这样:
0: "http://www.example.com/1"
1: "http://www.example.com/2"
但我希望它看起来像这样:
0: example1
1: example2
非常感谢。
$(element).attr('href')
==> 获取 href 属性 : link
$(element).text()
==> 获取文本
改成这样:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).text());
});