cheerio / jquery selectors: how to get text in tag a?

夙愿已清 提交于 2020-02-24 09:29:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!