简体   繁体   中英

Playwright - Find multiple elements or class names

I have read a few different QAs related to this but none seem to be working.

I am trying to target an element (Angular) called mat-radio-button with a class called mat-radio-checked. And then select the inner text.

In Chrome this is easy:

https://i.stack.imgur.com/Ev0iQ.png

https://i.stack.imgur.com/lVoG3.png

To find the first element that matches in Playwright I can do something like:

      let test: any = await page.textContent(
      "mat-radio-button.mat-radio-checked"
    );

    console.log(test);

But if I try this:

      let test: any = await page.$$(
      "mat-radio-button.mat-radio-checked"
    );

    console.log(test);
    console.log(test[0]);
    console.log(test[1]);
  });

It does not return an array of elements I can select the inner text of.

I need to be able to find all elements with that class so I can use expect to ensure the returned inner text is correct, eg:

    expect(test).toBe("Australian Citizen");

I found out the issue was due to the page generating beforehand and the elements were not available. So I added a waitForSelector:

await page.waitForSelector("mat-radio-button");

const elements = await page.$$("mat-radio-button.mat-radio-checked");
console.log(elements.length);
console.log(await elements[0].innerText());
console.log(await elements[1].innerText());
console.log(await elements[2].innerText());
  public async validListOfItems(name) {
  await this.page.waitForSelector(name, {timeout: 5000});
  const itemlists = await this.page.$$(name);

  let allitems: string[]=new Array();

    for await (const itemlist of itemlists) {
        allitems.push(await itemlist.innerText());
    }
  return allitems;
  }

Make a common method and call by sending parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM