Rayrun

How do I locate and interact with a button using Playwright?

Answer

Question: How do I find a button using @playwright/test?

Answer:

To find a button with Playwright, use locators based on user-facing attributes like role, text, and test id locators. This makes your selectors resilient to DOM changes.

Here's an example of finding a button by its role and text:

import { test, expect } from '@playwright/test';

test('Find a button', async ({ page }) => {
  await page.goto('https://ray.run/');

  const button = await page.locator('button:has-text("Submit")');
  await button.click();

  // Add your assertions here
});

You can also chain and filter locators to narrow down your search. For instance, find an item with text "Product 2" within a list and click on its "Add to cart" button:

import { test, expect } from '@playwright/test';

test('Find a button within a list item', async ({ page }) => {
  await page.goto('https://ray.run/');

  const listItem = await page.locator('li:has-text("Product 2")');
  const addToCartButton = await listItem.locator('button:has-text("Add to cart")');
  await addToCartButton.click();

  // Add your assertions here
});

Use Playwright's test generator to automatically generate tests and pick locators for you. Run the codegen command followed by the URL:

npx playwright codegen ray.run

In summary, use resilient locators based on user-facing attributes, chain and filter locators, and leverage tools like the test generator to find buttons with Playwright.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].