Home > Software design >  Access to Sibling element in Playwright
Access to Sibling element in Playwright

Time:08-05

I have two sibling spans in my DIV. I am doing E2E testing in Blazor and I want to access the second Span content (@Status).

<div>
     <span> Status:</span>
     <span> @Status</span>
 </div>

I found a solution for it, if it was JavaScript according to this link.

const text = await page.locator(':text(" Status:")   span').textContent();

However, I am not sure how to do the same for C# syntax. I have access to the first span but not next one.

var firstSpan = Page.Locator("text= Status :");

CodePudding user response:

You can use the selecting selectors based on layout for this.

await page.Locator("span:below(:text(\" Status :\"))").TextContentAsync()

CodePudding user response:

IMO relative positioning is flaky if there's fluid layout on the page.

:below() can switch to :right-of() if page css layout changes, eg flexbox.

Is there any reason you don't use simple

// invert double and single quotes for c#
const text = await Page.locator(":text(' @Status:')").textContent();

OR you original is perfect with quote marks inverted

const text = await page.locator(":text(' Status:')   span").textContent();

If you want to use relative layout, :near() would be better

await Page.locator("span:near(:text(' Status:'))").first().textContent();
  • Related