playwright
playwright copied to clipboard
[Feature] Automatic CSS Selector generator
It would be really great if playwright could generate unique CSS and XPATH selectors natively for ElementHandle. Because sometimes we need functionality to generate new selectors for future use.
Like this:
selectorDict = ElementHandle.selectorPattern()
print(selectorDict)
"""
{
"css": "article .test > p",
"xpath": "//article[@class='test']/p"
}
"""
I hope others would need this sort of feature as well
Doesn't playwright inspector already do this in a way it considers most effective?
CSS and XPath selectors are tied to implementation and are usually not the best choice for a selector: https://playwright.dev/docs/selectors#best-practices. Furthermore, ElementHandle
s are discouraged. Locator
should be used instead.
Doesn't playwright inspector already do this in a way it considers most effective?
Yes-ish. It's based on heuristics, so once it generates a selector, you'll want to review and edit for what makes sense for your app.
@puniaze If you still want XPath or CSS, you can use the browser's own DevTools to get the string:


For generating selectors with Playwright, see also https://playwright.dev/docs/next/debug-selectors
@rwoll I need to get selectors dynamically and programmatically on the fly. I am aware of DevTools feature
BTW. ElementHandle just for example, it can be locator as well.
Can you please suggest me something or can you re-label this issue as Feature request?
I've pre-emptivley converted to a feature request. However, can you elaborate on your use case and why you need to XPath or CSS selector programmatically?
Playwright allows you to run any JS code in the page, so you could write and/or use a third party package alongside page.evaluate(…)
that takes you from element and gives you a selector of your choosing.
@rwoll App is so dynamic and clicking on something would make changes on DOM. I want to get all changes in form of css selectors so I can programmatically perform actions
App is so dynamic and clicking on something would make changes on DOM. I want to get all changes in form of css selectors so I can programmatically perform actions
Can you elaborate on this? It's still not clear how this would be used even if we added it. Please walk us through end-to-end what you're trying to do. Is this part of a test case, or some automation/scraping?
(You can look into using MutationObserver in the page combined with Playwright's https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-binding to pass changed nodes back to Playwright. However, I cannot provide more information on this without first understanding the context more. Perhaps there is better/idiomatic to achieve what you want.)
Closing per-above as part of triage. Please re-file as a feature request with the requested information about use case if this is still an issue.
Thanks!