'How to get attribute value of an element in Playwright Python
I'm using Playwright Python for a project. I'm trying to get the 'href' attribute value of an element.
For Selenium, I used
el = driver.find_element_by_xpath("//a")
link = el.get_attribute('href')
What is the equivalent to the above code in Playwright?
Solution 1:[1]
You can access the href in an almost similar way to that of selenium.
element_handle = page.locator("//a")
link = element_handle.get_attribute('href')
Solution 2:[2]
You can try to use this code to obtain and print all the hrefs elements of a page. Empty field if it doesn't exist. I'm sure that then, you can obtain the element that you need
const urls = await page.$$eval('a', (elements) =>
elements.map((el) => el.href),
)
for await (const u of urls) {
console.log("URLS: " + u)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dennis |
| Solution 2 | Albert |
