javascript - Puppeteer 从 <dl> 结构中获取元素

标签 javascript node.js puppeteer dom-manipulation

我正在尝试获取如下结构中的元素:

<dl class="foo-bar">
    <dt>Key</dt>
    <dd>Value<dd>
    <dt>Key</dt>
    <dd>Value<dd>
    ....
</dl>

这是我想用纯 JS 做的:

let list = document.querySelectorAll('.foo-bar')

let key = list[0].children[0].innerText // would give me "Key"

这是我所在的地方:

let list = await page.evaluate(() => Array.from(document.querySelectorAll('.foo-bar'), element => element))

let key = list[0] //returns empty object ({})

编辑: 我需要访问所有 dt 键/值。最好将它们添加到这样的对象中:

let object = {
    key1: "key1",
    value1: "value1",
    key2: "key2",
    value2: "value2"
}

我知道对象的结构没有多大意义,但它并不是真正相关。

最佳答案

.foo-bar dt, .foo-bar dd选择器应该为您提供所有 <dt> 的数组和 <dd>嵌套在 <dl class="foo-bar"></dl> 中的元素.

const list = await page.evaluate(() => document.querySelectorAll('.foo-bar dt, .foo-bar dd'));

const key = list[0].innerText;

或者,您可以使用 $$() page method ,本质上是 document.querySelectorAll() .这是一个例子:

const list = await page.$$('.foo-bar dt, .foo-bar dd');

const key = list[0].innerText;

这是一个如何使用 reduce() 的示例在您的数组上将其转换为您需要的对象:

// Stubbing the list data for example.
const list = [
  { innerText: 'key1' },
  { innerText: 'value1' },
  { innerText: 'key2' },
  { innerText: 'value2' },
  { innerText: 'key3' },
  { innerText: 'value3' }
]

const test = list.reduce((acc, v, i) => {
  // Map even items as properties and odd items as values to prev property.
  i % 2 === 0 ? acc[v.innerText] = null : acc[list[i-1].innerText] = v.innerText;
  return acc;
}, {});

console.log(test);

关于javascript - Puppeteer 从 <dl> 结构中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102472/

相关文章:

javascript - 裁剪掉图像中的所有白色

javascript - 如何在取消选中 AngularJS 中的复选框时刷新下拉菜单

javascript - 在 NodeJS 中导出 API 对象

javascript - Bitbucket 管道和非 headless Puppeteer?

javascript - 从网页打印选定的数据

javascript - 如何附加事件监听器来动态生成单选按钮?

node.js - 如何查看nodejs中readline模块的源代码?

javascript - Passport.js 回调总是出错

node.js - 使用 xvfb headless : false 运行 Puppeteer

javascript - 异步函数抛出错误,但我看不到它们