Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 木偶演员从a<;dl>;结构_Javascript_Node.js_Puppeteer_Dom Manipulation - Fatal编程技术网

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
元素