【问题标题】:How do I refer to "this" inside filter function of querySelectorAll?如何在 querySelectorAll 的过滤函数中引用“this”?
【发布时间】:2023-03-07 00:30:01
【问题描述】:

我的 Cheerio 代码如下所示:

const title = $("meta")
            .filter(function () {
              return (
                ($(this).attr("property") != null &&
                  $(this).attr("property").endsWith("title")) ||
              );
            }).attr("content")

我想将此迁移到使用客户端 javascript 的 puppeteer。到目前为止我有这个:

const title = Array.from(document.querySelectorAll("meta")
            .filter(function () {
              return {
              // stuck here: how do I call this?
              // $(this)

我被困在如何使用文档查询选择器语法来引用“this”。

【问题讨论】:

  • 请注意,问题中的代码可以完全重写为const elem = document.querySelector("meta[property$='title']); const title = elem && elem.getAttribute("content"); 同样,您的答案中的代码只是document.queySelectorAll("meta[name$='title']")

标签: javascript jquery web-scraping puppeteer cheerio


【解决方案1】:

使用Array.prototype.filter的第一个参数,表示当前被迭代的元素。

或者,由于您似乎只想要 first 匹配,请改用 .find

const title = Array.from(document.querySelectorAll("meta"))
  .find(function (meta) {
    return String(meta.getAttribute('property')).endsWith("title");
  })
  .getAttribute('content');

你也可以在 Cheerio 中做同样的事情,除了被迭代的元素 both 放入this 放入第二个参数。

const title = $("meta")
.filter(function (_, meta) {
  return (
    ($(meta).attr("property") != null &&
     $(meta).attr("property").endsWith("title"))
  );
}).attr("content")

(但this一般与cheerio和jQuery搭配使用)

【讨论】:

    【解决方案2】:

    我想通了!您只需在回调中输入一个参数。早该知道的。

    例如:

    Array.from(document.querySelectorAll("meta")
                .filter(function (el) {
                  return el.name !== null && el.name.endsWith("title")
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2017-03-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      相关资源
      最近更新 更多