In this tutorial, we’ll walk you through how to use Playwright’s getAttribute() method in JavaScript to retrieve element attributes with a real-world example.
Why Get Element Attributes in Playwright?
When testing or scraping web pages, attribute values help determine:
- The link target (href)
- Image source (src)
- Input states (value, placeholder, etc.)
- Custom data attributes (data-*)
- Accessibility attributes (aria-*)
Retrieving these values lets you validate UI behavior, extract data, or make logic-based decisions in your scripts.
✅ Syntax fetching element attribute
await locator.getAttribute(attributeName);
✅ Syntax fetching element attribute Using evaluate()
const title = await page.locator('img#logo').evaluate((el) => el.getAttribute('title'));
Example for Getting Element Attributes
Simple and straightforward example.
import { test, expect } from '@playwright/test'; test('get element attribute', async ({ page }) => { await page.goto('https://example.com'); const href = await page.locator('a').first().getAttribute('href'); console.log('Href:', href); // Output: Href: https://www.iana.org/domains/example });
Using getAttribute() in Playwright is straightforward but powerful. Whether you’re building automated tests or scraping websites, accessing element attributes can provide deep insights into your page’s structure and behavior.
No comments:
Post a Comment