Javascript 木偶演员从a<;dl>;结构
我试图得到一个结构中的元素,如下所示:Javascript 木偶演员从a<;dl>;结构,javascript,node.js,puppeteer,dom-manipulation,Javascript,Node.js,Puppeteer,Dom Manipulation,我试图得到一个结构中的元素,如下所示: 钥匙 价值 钥匙 价值 .... 这就是我想在纯JS中做的: let list=document.querySelectorAll(“.foo-bar”) let key=list[0]。子项[0]。innerText//将给我“key” 这就是我所处的位置: let list=wait page.evaluate(()=>Array.from(document.queryselectoral('.foo-bar'),element=>element
钥匙
价值
钥匙
价值
....
这就是我想在纯JS中做的:
let list=document.querySelectorAll(“.foo-bar”)
let key=list[0]。子项[0]。innerText//将给我“key”
这就是我所处的位置:
let list=wait page.evaluate(()=>Array.from(document.queryselectoral('.foo-bar'),element=>element))
let key=list[0]//返回空对象({})
编辑:
我需要访问所有dt
键/值。最好将它们添加到如下对象:
let对象={
键1:“键1”,
value1:“value1”,
键2:“键2”,
值2:“值2”
}
我知道对象的结构没有多大意义,但它并不真正相关。如果您只需要第一个
dt
文本,您应该直接请求:
await page.evaluate(() => document.querySelector('.foo-bar dt').innerText)
.foo-bar-dt、.foo-bar-dd
选择器应为您获取嵌套在
中的所有
和
元素的数组
const list=wait page.evaluate(()=>document.queryselectoral('.foo-bar-dt,.foo-bar-dd'));
常量键=列表[0]。innerText;
或者,您可以使用,它本质上是document.querySelectorAll()
。下面是一个例子:
const list=wait page.$$('.foo-bar-dt,.foo-bar-dd');
常量键=列表[0]。innerText;
下面是一个示例,说明如何在数组上使用reduce()
,将其转换为所需的对象:
//例如,存根列表数据。
常数列表=[
{innerText:'key1'},
{innerText:'value1'},
{innerText:'key2'},
{innerText:'value2'},
{innerText:'key3'},
{innerText:'value3'}
]
常量测试=列表减少((acc,v,i)=>{
//将偶数项作为属性映射,将奇数项作为值映射到prev属性。
i%2==0?acc[v.innerText]=null:acc[list[i-1]。innerText]=v.innerText;
返回acc;
}, {});
控制台日志(测试)代码>调整@Vaviloffs答案解决了问题
我只是创建了一个包含所有dt
和dd
元素的数组
let list = await page.evaluate(() => Array.from(document.querySelectorAll('.foo-bar dt, .foo-bar dd'), element => element.textContent))
我发现我最初的问题有点不清楚,但现在我已经更新了。我需要访问所有dt
元素