Cheerio:.text()将所有元素的文本附加在一起

时间:2018-12-29 01:14:51

标签: javascript cheerio

下面的代码输出所有带staff-member-title附加的p标签

let arr = [];

$("li.staff-directory-department").map((item, index) => {
  arr.push({
    title: $("p.staff-member-title", index).text()
  });
});

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="staff-directory">
  <li class="staff-directory-department">
    <h2 class="staff-directory-department">
      Academic Affairs
    </h2>
    <ul class="staff-directory-department-list">
      <li class="staff-member ">
        <a href="" class="staff-member-image">
          <img src="" />
        </a>
        <h3 class="staff-member-name">
          <a href="">Meli</a>
        </h3>
        <p class="staff-member-title">Director of Institutional Research & Effectiveness</p>
        <p class="staff-member-email">
          <a href="mailto:"></a>
        </p>
        <p class="staff-member-phone"><a href="tel:">(90</a></p>
      </li>
    </ul>
  </li>
</ul>

arrayInfo的当前输出:

[
  { title: 'Director of Institutional Research & EffectivenessAdministrative AssistantDirector of Online Learning and Educational TechnologyAssociate Vice President of Academics and Strategic InitiativesVice President for Academics & Student Life' },
  { title: 'Director of Institutional Research & EffectivenessAdministrative AssistantDirector of Online Learning and Educational TechnologyAssociate Vice President of Academics and Strategic InitiativesVice President for Academics & Student Life' },
  ...
]

预期输出:

[
  { title: 'Director of Institutional Research & Effectiveness' },
  { title: 'Administrative Assistant' },
  ...
]

2 个答案:

答案 0 :(得分:0)

我相信您的问题是您正在使用Javascript创建字典,但是将一个键提供给多个项目,因此,当调用该键时,您将拉出与该键相关联的每个项目。

您可能想要尝试的是将所有Titles放入一个数组中,然后将该数组与键Title关联,以便在调用键Title时可以在所有Title数组中进行筛选。

let arr = [];
let titleArr = [];

$("li.staff-directory-department").map((item, index) => {
  titleArr.push({
    $("p.staff-member-title", index).text()
  });
});

arr.push({title: titleArr});

然后,当您要获取标题时,只需使用键调用数组即可:

for(var x = 0; x < titleArr.length; x++){
    console.log(arr["title"][x]);
}

答案 1 :(得分:0)

您正在混淆参数,索引在Cheerio.map中排在首位

let arr = $('li.staff-directory-department').map((i, el) => {
  return { title: $(el).find('p.staff-member-title').text() }
}).get()

使用Array.map可能更简单

let arr = $('li.staff-directory-department').get().map((el) => {
  return { title: $(el).find('p.staff-member-title').text() }
})

注意:get()将cheerio对象变成一个数组。