Playwright >> Getting and setting (text, html, input value, attribute, href, localstorage, cookie, user agent, viewport/resolution/window size, and headers)

2022-05-17 Playwright

Table of Contents

This tutorial will explain how to get text, html, input value, attribute, href of element, and how to get the localstorage, cookie.
And explain how to set localstorage, cookie, input value of textbox, user agent, viewport/resolution/window size, and custom headers of the browser.

Playwright

Playwright get Text of element

# Get Text of element
element = page.locator('a:has-text("playwright")').first
print(element.inner_text())

Playwright get the inner HTML of element

element = page.locator('a:has-text("playwright")').first
print(element.inner_html())

Playwright get the input value of textbox

element = page.locator('input[name="q"]')
print(element.input_value())

Playwright get attribute value of element

element = page.locator('input[name="myButton"]')
print(element.get_attribute("value"))

We can use the get_attribute method to get the href attribute of an element.

element = page.locator("a:has(h3)").nth(1)
print(element.get_attribute("href"))

Playwright get localstorage item

We can use the evaluate method of page to call the api to get the item stored in the localstorage.

page.evaluate("window.localStorage.getItem('myCat', 'Tom');")

We can use the cookies() method of browserContext object to set the cookie.

browser_context = browser.new_context()
cookie = context.cookies("https://www.google.com/") # specify URL
print(cookie)

Playwright set localstorage item

We can use the evaluate method of page object to call the api to set the item stored in the localstorage.

# Set localstorage
page.evaluate("window.localStorage.setItem('myCat', 'Tom');")

Playwright

We can use the add_cookies() method of browserContext object to set the cookie.

browser_context = browser.new_context()
browser_context.add_cookies([{"name": "myCookie", "value": "cookieValue", "url": "https://www.google.com/"}]) 

Playwright set input value of textbox

page.type('input[name="q"]', "my content") # types instantly
page.type('input[name="q"]', "my content", delay=100) # types slower, like a user

Playwright set viewport/resolution/window size

context = browser.new_context(
    viewport={ 'width': 1920, 'height': 1024 }
)

Playwright set user agent

context = browser.new_context(
  user_agent='Your custom user agent'
)

Playwright set custom header

page.set_extra_http_headers({"myHeader" : "myValue"})

Playwright

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us