Playwright: [Question] How to query element by containing text

Created on 18 May 2020  路  9Comments  路  Source: microsoft/playwright

Is there a way similar to cssContainingText in protractor. I have to query a element by its text content.

image

I have to get the element which contains the text 'START' among the other three.

Most helpful comment

Playwright does provide a way to chain CSS and text selectors together. Have a look at this section of the docs.
https://playwright.dev/#version=v1.0.2&path=docs%2Fselectors.md&q=selector-syntax

In your case, it might look something like this.

await page.$('css=#designer-surface >> css=svg >> css=text >> css=tspan >> text="START"');

All 9 comments

Playwright does provide a way to chain CSS and text selectors together. Have a look at this section of the docs.
https://playwright.dev/#version=v1.0.2&path=docs%2Fselectors.md&q=selector-syntax

In your case, it might look something like this.

await page.$('css=#designer-surface >> css=svg >> css=text >> css=tspan >> text="START"');

@celeryclub It worked awesome.

await page.$('css=#designer-surface >> css=svg >> css=text >> css=tspan >> text="START" >> xpath=preceding-sibling::*[2]');

Can I append a xpath after the text node? Will the above one work?

As far as I know. Did you try it?

I tried it but did not work. I not sure what i am missing

I don't think there's really a way to debug this without seeing a minimal reproduction of the failure. Can you create a failing case using https://codesandbox.io/ or something like that?

I tried it but did not work. I not sure what i am missing

@Bharath-Kumar-S can you show us what you tried? We might be able to spot something right away.

await page.$('css=#designer-surface >> css=svg >> css=text >> css=tspan >> text="START" >> xpath=preceding-sibling::*[2]');

@celeryclub while this would work, you can actually simplify things:

await page.$('css=#designer-surface svg text tspan >> text="START" >> xpath=preceding-sibling::*[2]');

@aslushnikov I tried like this

const cy = await (await page.$('#designer-surface > svg > text > tspan')).$eval('preceding-sibling::*[2]', el => el.getAttribute('cy')); console.log(cy)

const cy = await (await page.$('#designer-surface > svg > text > tspan')).$eval('preceding-sibling::*[2]', el => el.getAttribute('cy'));
   console.log(cy)

Try the following. Note xpath= prefix - we do not autodetect preceding-sibling::*[2] as xpath.

const cy = await (await page.$('#designer-surface > svg > text > tspan')).$eval('xpath=preceding-sibling::*[2]', el => el.getAttribute('cy'));

Or simpler:

const cy = await page.$eval('#designer-surface > svg > text > tspan >> xpath=preceding-sibling::*[2]', el => el.getAttribute('cy'));

Assuming this is resolved. Please feel free to reopen!

Was this page helpful?
0 / 5 - 0 ratings