【问题标题】:Filter out all instances of a div class using cheerio使用cheerio过滤掉一个div类的所有实例
【发布时间】:2022-01-01 05:10:50
【问题描述】:

这里是 Cheerio / nodeJS 新手...为真正的恶棍保留讽刺。

我正在尝试从 div 类 exchange-card-small-logo > a > img 中提取 title(在本例中为“Alfaash”)。 HTML 中可能有这个 div 类的多个实例。我正在尝试从每个实例中提取 title

console.log 不会在以下情况下受到攻击:

axios.get("https://cryptoradar.co/exchanges")
    .then(response => {
        const html = response.data
        const $ = cheerio.load(html)

        $('.exchange-card-small-logo', html).each(function () {
            console.log($(this).length)
        })

这两个log都返回0:

const elems = $('.exchange-card-small-logo', html);
console.log(elems.length);
console.log(elems.toArray().length);

还有,这个:

const elems = $('.exchange-card-small-logo', html);
console.log(elems);

返回:

LoadedCheerio {
  length: 0,
  options: { xml: false, decodeEntities: true },
  _root: <ref *1> LoadedCheerio {
    '0': Node {
      type: 'root',
      name: 'root',
      parent: null,
      prev: null,
      next: null,
      children: [Array],
      'x-mode': 'no-quirks'
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: [Circular *1]
  },
  prevObject: LoadedCheerio {
    '0': Node {
      type: 'root',
      name: 'root',
      parent: null,
      prev: null,
      next: null,
      children: [Array]
    },
    length: 1,
    options: { xml: false, decodeEntities: true },
    _root: <ref *1> LoadedCheerio {
      '0': [Node],
      length: 1,
      options: [Object],
      _root: [Circular *1]
    },
    prevObject: LoadedCheerio {
      length: 0,
      options: [Object],
      _root: [LoadedCheerio]
    }
  }
}

这是 CSS 选择器:#results &gt; div &gt; div.main-container.grid-flex &gt; div:nth-child(1) &gt; div.exchange-card-small-images &gt; div.exchange-card-small-logo

我无法使用cheerio 将层次结构一直到该div 类。有没有办法在不遍历所有路径的情况下过滤掉这个类的所有实例?

【问题讨论】:

  • 为什么不简单地 .exchange-card-small-logo 呢?它将选择所有实例
  • 它是空的。
  • 空了?这很奇怪,因为元素显然在 HTML 结构中。您确定您的 Cheerio 选择器与上面显示的内容相反吗?并且它不会在 渲染 HTML 或其他任何东西之前运行?
  • @JeremyThille 使用代码 sn-p 编辑问题。
  • 啊啊啊不,我知道。该网站是使用 Ajax 动态构建的。 Axios 为您提供原始 HTML,但不执行任何脚本。要查看 Axios 为您带来了什么,请禁用页面上的 Javascript 并重新加载它。只有一个绿色的无限装载机。您需要一个像Puppeteer 这样的无头浏览器,它将使用 Javascript 和 Ajax 调用呈现整个页面。一个简单的 HTTP 调用无法满足您的需求。

标签: javascript html css node.js cheerio


【解决方案1】:

imgs 在 html 中,我可以看到它们。

$('.exchange-card-small-logo img').get().map(img => $(img).attr('title'))

【讨论】:

  • 这对你有用吗?我得到一个空数组
  • 它适用于那个 html,你可能被服务器阻止了。尝试发送一些请求标头。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 2016-08-15
  • 2012-02-21
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多