我正在尝试使结构中的元素看起来像这样:
<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"
}
我知道对象的结构没有多大意义,但实际上并没有相关性。
答案 0 :(得分:1)
.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);
答案 1 :(得分:0)
如果仅需要前dt
个文本,则应直接请求它:
await page.evaluate(() => document.querySelector('.foo-bar dt').innerText)
答案 2 :(得分:0)
调整@Vaviloffs答案可以解决问题!
我只是使用
创建所有dt
和dd
元素的数组
let list = await page.evaluate(() => Array.from(document.querySelectorAll('.foo-bar dt, .foo-bar dd'), element => element.textContent))