问题描述
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”。
解决方法
使用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中执行相同的操作,除了要迭代的元素都是 放入this
中参数。
const title = $("meta")
.filter(function (_,meta) {
return (
($(meta).attr("property") != null &&
$(meta).attr("property").endsWith("title"))
);
}).attr("content")
(但是this
通常用于cheerio和jQuery)
我知道了!您只需要在回调中加入一个参数即可。应该知道的。
例如:
Array.from(document.querySelectorAll("meta")
.filter(function (el) {
return el.name !== null && el.name.endsWith("title")