2

I want to retrieve the full XPATH (\\html\div\...) of an element I have previously found via e.g. page.waitForSelector() or page.querySelector().

How would I do this with Playwright? I was not able to find any built-in solutions for this.

NOTE: I am using playwright-python, but would be open to implementing JS solutions for this - given it will work.

Template (taken from https://github.com/microsoft/playwright-python sample code):

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    for browser_type in [p.chromium, p.firefox, p.webkit]:
        browser = browser_type.launch()
        page = browser.new_page()
        page.goto("http://whatsmyuseragent.org/")
        element = page.waitForSelector(selector="text=\"My IP Address: 192.168.0.1\"")
        # HERE: retrieve full XPATH of 'element'
        browser.close()

EDIT:

@hardkoded suggested the answers to this question (Get element's xpath in javascript) as a solution, but sadly the mentioned solution does not work for my use-case as I would need to retrieve the entire XPATH of an element, and shortcuts like //*[@id="THE_ID"] will not work for me.

jån
  • 165
  • 1
  • 9
  • Does this answer your question? [Get element's xpath in javascript](https://stackoverflow.com/questions/16731640/get-elements-xpath-in-javascript) – hardkoded Feb 22 '21 at 11:14
  • 1
    @hardkoded Sadly not, as I would need to retrieve the complete XPATH of an element and shortcuts like `//*[@id="THE_ID"]` sadly will not work for my purposes. Thank you for linking the question though! – jån Feb 22 '21 at 15:59
  • Just as a hint. Look for JavaScript snippets that you can run from puppeteer. Puppeteer doesn't have anything for that out of the box. – hardkoded Feb 22 '21 at 18:49
  • Does this answer your question? [How to calculate the XPath position of an element using Javascript?](https://stackoverflow.com/questions/3454526/how-to-calculate-the-xpath-position-of-an-element-using-javascript) – ggorlen Dec 03 '22 at 16:15

1 Answers1

0

For Typescript/Javascript there is playwright-dompath which you can install with:

npm install playwright-dompath

Basically you just call the xPath function with the element you selected, and you get back the full xPath. Under the hood, it uses the same functions from Chrome DevTools.

mrgorefest
  • 81
  • 5