CSS Selector in Playwright Java

Profile picture for user arilio666

In Playwright Java, you can use several basic CSS selectors to locate elements on a web page.

Element Selector

We can use a CSS selector based on a tag name; for example, to select all the input elements from a page, use this.

page.locator("input");

ID Selector

We can select an element by its ID using the # character. For example, select an element with an ID of "edit-name."

page.locator("#edit-name");

Class Selector

We can select an element by its class using the "." character. For example, to select an element with a class of "role-sel."

page.locator(".role-sel");

Attribute Selector

We can select an element by its attribute using square brackets. For example, to select an element with a value attribute of "four."

page.locator("[value='four']");

Combining Selectors

We can combine different selectors to select elements that meet multiple criteria. For example, to choose a div element with a class of "role-sel."

page.locator("div.role-sel");

Selecting visible elements

We can also select elements based on tag and :. For example, select a button tag with visible element fruit.

page.locator("button:fruit");

Selecting elements that contain other elements

:has() is an experimental CSS pseudo-class. This returns any elements when passed within the parameters relative to the :scope.

page.textContent("input:has(div.role-sel)");

Conclusion:

These are just a few examples of the basic CSS selectors you can use in Playwright Java to locate elements on a web page. You can also use more complex selectors, such as child selectors and sibling selectors, to find specific elements on a page.