问题
I am trying to access links on a website. The website looks like the first code sample and the links are in different 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>
I did tried to extract the links with this code:
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).attr('href'));
});
But the outputs look like this:
0: "http://www.example.com/1"
1: "http://www.example.com/2"
But I want it to look like this:
0: example1
1: example2
Thank you very much.
回答1:
$(element).attr('href')
==> get href property : the link
$(element).text()
==> get text
just change like this :
var list = [];
$('div[id="list"]').find('a').each(function (index, element) {
list.push($(element).text());
});
来源:https://stackoverflow.com/questions/48379384/cheerio-jquery-selectors-how-to-get-text-in-tag-a