Home > database >  Having difficulty with xpath function text()
Having difficulty with xpath function text()

Time:03-03

I wrote a really simple test, navigate to a page after logging in, and clicking an element once the page is loaded

In my selenium project I use the xpath text() function to help me look for specific icons in the app im automating

I was wondering how to do that with playwright

here is my test, it uses the page object modal in the playwright documentation

test('Navigate using POM', async ({ page }) => {
  await page.goto('/db');
  const mainView = new MainView(page);
  mainView.selectSampleInSideNav();
});

the problem is the icon I need to click on is defined by a specific text in the HTML, but that exact text is used on another element so I cannot write something like(also it has the white spaces in the html as well)

await page.click('text= Sample ');

Is there a way to write this xpath expression in playwright?

"//mat-icon[text()=' Sample ']"

I've tried something like this:

const sideNavSample =  page.$('mat-icon >> text=" Sample "');

but i get a Cannot read property of 'click' of undefined when i try to interact with sideNavSample

await this.sideNavSample.click();

Any help would be wonderful, as Xpath is the only way I can define a unique identifier for this specific icon. Apologies if this is a dumb question

@archon thank you for the suggestion but it seems that when I write out the click action exactly the way you have it written it works just fine, but when I store it in a variable it fails. I cant explain why but this works page.click('//mat-icon[contains(text(), "Sample")]')

this does not this.sampleOptionInSideNav = page.locator('//mat-icon[contains(text(), " Sample ")]'); await this.reviewOptionInSideNav.click();

CodePudding user response:

text()='x' pattern looks for an exact text match. You can try page.click('//mat-icon[contains(text(), "Sample")]').

For strict matching, you should use text-is, and for selecting mat-icon with strict text rules, this await page.locator('mat-icon :text-is(" Sample ")') can work.

  • Related