Retrieve list of all the elements on a page

109 views Asked by At

I clearly don't understand how locators work.
How do I retrieve a list of all the elements on a page where the name matches a pattern?

    // this was translated from javascript
    public async Task<List<string>> ListOfItems(IPage page, string pattern) {
        await page.WaitForSelectorAsync('.' + pattern);
        var itemlists = await page.$$(pattern); // this doesn't translate

        List<string> allitems = new List<string>();

        foreach (var itemlist in itemlists) {
            allitems.Add(await itemlist.innerText());
        }
        return allitems;
    }

My immediate use case is a page that should have a list of items displayed from the database. If there are 5 items in the database, there should be 5 items in the list. I thought this might be a generally useful routine, but I don't have any other specific use cases yet.

---update---
This looks promising.
Tries to use partial CSS selectors, so I can select on name, class, or id.
On the downside, it doesn't use the playwright API.
But gives 'Unexpected token "^=" while parsing selector "id^=note"'

    Assert.AreEqual(5, (await ListOfItems(page, "id^=note")).Count());

    public async Task<List<string>> ListOfItems(IPage page, string pattern) {
        var locator = page.Locator(pattern);
        var itemlist = await locator.AllAsync(); //fails here
        List<string> allitems = new List<string>();

        foreach (var item in itemlist) {
            // Get the element handle for the item
            var element = await item.ElementHandleAsync();
            // Get the inner text for the element
            var text = await element.InnerTextAsync();
            allitems.Add(text);
        }
        return allitems;
    }
2

There are 2 answers

0
akshat narang On BEST ANSWER

You are missing [] around id^=note. The syntax of the CSS selecto should be [attribute^=value]. So, the correct CSS selector is

[id^="note"]
2
Vishal Aggarwal On

This is how CSS selector should look like in this case as [attribute^=value]

'*[id^="note"]'

' * ' simply means , the element type(tag) can be of any kind like div or button or anything however it must have the unique property called "id" having the value as "note" to start with.

Reference: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors