Playwright Handling Attributes of WebElement

ntroduction

In this blog, we will understand how to handle attributes of a WebElement in Playwright.

Prerequisite

While working in Test Automation, we will come across scenarios to get the value of attributes and text of elements from the webpage. We may need to use these values to apply assertions in your test.

Text of Element

The text of the element is the text which is found in between any HTML tag.

Example

<div id='test> tesing</div>

Markup

Copy

To get the text, we need to use textcontent function.

await page.goto("https://the-internet.herokuapp.com/");
const gettext= await page.locator("//h1").textContent();
console.log('text of element,',gettext);

JavaScript

Copy

getattribute of element

Attributes of web elements can be extracted using the getAttribute function. This function takes an html attribute name as an argument.

As you can see in the below code block, I want to get the placeholder attribute value of the text box element; hence I have passed the attribute name in the getattribute function.

const attributevalue=await page.locator('#name').getAttribute('placeholder');
console.log('attribute of texbox',attributevalue);

JavaScript

Copy

Get the CSS property of the element

To get the css property of the element, we need to use evaluate API. The page.evaluate() API can run a JavaScript function in the context of the web page and bring results back to the Playwright environment. Browser globals like Windows and documents can be used in the evaluation.

So we use the window object, the getcomputed function, and the getproperty function to get the desired css property of the element.

const cssproperty=await page.locator('#alertbtn');
const color = await cssproperty.evaluate((e) => {
        return window.getComputedStyle(e).getPropertyValue("background-color")
    })
console.log('color,',color);
const fontsize = await cssproperty.evaluate((e) => {
        return window.getComputedStyle(e).getPropertyValue("font-size")
    })

JavaScript

Copy

Summary

I hope this blog will be helpful in handling attributes of webelement in a webpage using Playwright Test Automation Project.

Thanks, Happy learning

Ebook Download
View all
Learn
View all