木偶动态选择器返回多个对象

时间:2020-04-03 05:17:52

标签: javascript dom automated-tests puppeteer e2e-testing

dom tree

这是我的DOM树的样子。我使用的操纵up代码如下所示。

  const selector = '[class^="SubscriptionBilling_tierInclusion__"]';
  const nodes = Array.from(await page.$$(selector));
  const nodeList = Array.from(nodes).map(element => element);

在DOM结构中,“ SubscriptionBilling_tierInclusion __ ”重复多次,并在其中嵌套3个div。所有这些元素都有动态的类名,如图所示。

我需要获取这3个div的值(如第一块中的图像所示-HEADING,DESCRIPTION)

使用我尝试过的代码,我得到了元素的集合,但是不确定如何获取子对象的值。

2 个答案:

答案 0 :(得分:1)

page.$$解析为ElementHandle数组,因此Array.from是多余的。 您可以使用元素的children属性,并像这样获得前三个孩子的innerText:

const values = await page.$$eval('[class^="SubscriptionBilling_tierInclusion__"]', elements => elements.map(el => [...el.children].filter((el, index) => index < 3).map(el => el.innerText)))

如果需要在伪造者上下文中使用节点,则可以使用evaluateHandle

答案 1 :(得分:0)

您可以尝试这样的事情。

const selector = '[class^="SubscriptionBilling_tierInclusion__"]';
const nodes = document.querySelectorAll(selector); // Replace this JS code with Puppeteer's
const nodeList = Array.from(nodes).map(element => element);
const ChildNodesVal = [];
console.log(nodeList);
nodeList.forEach((e,i)=>
{
    ChildNodesVal[i] = [];
    e.querySelectorAll('div').forEach(child => ChildNodesVal[i].push(child.textContent))
});
console.log(ChildNodesVal);
<div class="SubscriptionBilling_tierInclusion__">
  <div class="first1">1</div>
  <div class="first2">2</div>
  <div class="first3">3</div>
</div>
<div class="SubscriptionBilling_tierInclusion__">
  <div class="first4">4</div>
  <div class="first5">5</div>
  <div class="first6">6</div>
</div>