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;
}
You are missing [] around id^=note. The syntax of the CSS selecto should be [attribute^=value]. So, the correct CSS selector is