Tal Angel
Tal Angel

Reputation: 1782

How to find element by attribute and text in a singe locator?

How can I find an element using Playwright using a single locator phrase?

My element is:

<div class="DClass">Hello</div>

I wish to find the element by its class and text:

myElement = self.page.locator('text="Hello",[class="DClass"]')

Why it does not work?

Upvotes: 5

Views: 9159

Answers (2)

ggorlen
ggorlen

Reputation: 56965

I suggest the following locator:

from playwright.sync_api import sync_playwright  # 1.40.0


with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.set_content('<div class="DClass">Hello</div>')
    loc = page.locator('.DClass:text-is("Hello")')
    print(loc.text_content()) # => Hello
    browser.close()

.DClass is generally preferred to [class=""] attribute syntax because it doesn't fail if other classes are present on the element. [class=""] is an exact match.

On the other hand, the :text-is("") pseudoselector is an exact match. Text is more often the sort of thing where you want exact precision, unlike CSS classes. But if you do want to use a substring on the text, :text("") is available.

If you're writing an assertion, you can use

expect(page.locator(".DClass")).to_have_text("Hello")

although keep in mind that CSS classes aren't user-visible and are discouraged for locators.

Upvotes: 1

hardkoded
hardkoded

Reputation: 21627

If you separate the selectors with a , that's an or. You can chain selectors using >>.

myElement = self.page.locator('text="Hello" >> [class="DClass"]')

Upvotes: 8

Related Questions