【问题标题】:Getting structured text from multiple classes从多个类中获取结构化文本
【发布时间】:2020-03-07 03:57:05
【问题描述】:

使用节点和cheerio 库处理scraper,并有一个基本问题。被抓取的网站具有类似于以下的结构:

<article class="featured h-event">
  // Lots of irrelevant stuff
  <div class="p-name">name goes here</div>
  // Lots of irrelevant stuff
    <div class="p-location">location</div>
  // Lots of irrelevant stuff
</article> 

我正在使用cheerio,它的逻辑类似于jquery,并使用以下代码:

var items = $(".featured.h-event")
  .map(function (i, el) {
    var x = cheerio.load(el)
    return { name: x(".p-name").text(), location: x(".p-location").text() }
    })
  .get()

这可行,但感觉应该有一种更简单/更快的方法来完成我想要做的事情。我对var xline 感到不舒服,这可能是在浪费资源。有没有更好的方法来做我想做的事情?

【问题讨论】:

  • 仅供参考,它是 scraper(以及 scrapingscrapedscrape)而不是 scrapper。 “废弃”意味着像垃圾一样扔掉:-(

标签: jquery node.js cheerio


【解决方案1】:

这应该可以满足您的需求,我们使用的代码少了一点,但结果应该相似:

const cheerio = require("cheerio");

let html = 
`<article class="featured h-event">
<!-- Lots of irrelevant stuff -->
<div class="p-name">name goes here</div>
<!-- Lots of irrelevant stuff -->
<div class="p-location">location</div>
</article>
<article class="featured h-event">
    <!-- Lots of irrelevant stuff -->
    <div class="p-name">name goes here #2</div>
    <!-- Lots of irrelevant stuff -->
    <div class="p-location">location #2</div>
</article>`;

const $ = cheerio.load(html);

const resultList = $(".featured.h-event").map((i, elem) =>  {
    return { name: $(".p-name", elem).text(), location: $(".p-location", elem).text()};
}).get();

console.log(resultList);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2016-09-07
    • 2021-08-31
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多