Search code examples
playwrightplaywright-python

Find first element above other element using Playwright


I have a div with text, for example 'abc'.

I wish to find the first div above that element that has a class called 'myClass'. How to do it? My code doesn't work:

self.page.locator(f'[class="myClass"] >> nth=0:'                                        
f'above(:text("abc"))').count()

Image example


Solution

  • You can do something like this:

    self.page.locator(f'div:above(:text("Security Notifications"))').count()
    //or
    self.page.locator(f'div:left-of(:text("Security Notifications"))').count()
    //or
    self.page.locator(f'div:near(:text("Security Notifications"))').count()