In Playwright, selectors are used to locate elements on the web page. Playwright supports a wide range of selectors to make it easier to target elements. Here are the different types of selectors available in Playwright:
- CSS Selectors: CSS selectors are widely used in web development to style elements. They can also be used in Playwright to select elements.
const elementHandle = await page.$('css=div > span');
- XPath Selectors: XPath is a language used for selecting nodes in an XML document. It can also be used to locate elements in HTML.
const elementHandle = await page.$('xpath=//div/span');
- Text Selectors: Text selectors allow you to select elements by their text content.
const elementHandle = await page.$('text="My Button"');
- ID Selectors: ID selectors allow you to select an element by its ID.
const elementHandle = await page.$('id=my-button');
- Data Attribute Selectors: These selectors allow you to select elements by their data attributes.
const elementHandle = await page.$('data-testid=my-button');
- JSHandle Selectors: These selectors allow you to select elements using JavaScript.
const jsHandle = await page.evaluateHandle(() => document.querySelector('button'));
- Tag Selectors: Tag selectors allow you to select an element by its tag name.
const elementHandle = await page.$('button');
- Attribute Selectors: Attribute selectors allow you to select an element by its attribute.
const elementHandle = await page.$('[my-attribute]');
- Class Selectors: Class selectors allow you to select an element by its class.
const elementHandle = await page.$('.my-class');
- Playwright Selectors: Playwright also supports its own selector engine that combines CSS, XPath, and text selectors.
const elementHandle = await page.$('css=div >> xpath=//span >> text="My Button"');
Each of these selectors has its own use cases and advantages. Depending on the complexity of the web page and the specific elements you need to target, you can choose the most suitable selector.