microsoft / playwright

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
https://playwright.dev
Apache License 2.0
66.31k stars 3.62k forks source link

[Question] Can I use regex to select a css selector based on class? #19289

Closed zac11 closed 1 year ago

zac11 commented 1 year ago

We can use a regex pattern, in the page.locator method to select an element - as mentioned in the example here.

I'm looking to see if I can use the same for a class based css locator ? For eg, I have this code block

<div class="testBanner__2JXbh">
<span class="test__11MBE">THIS IS A TEST ENVIRONMENT</span>
<span>Hello this is a test env." class="gotoUrl__2k_uk">https://your-abcdurl.com</a>
</div>

Can I use something like this

await page.locator('class=testBanner__/[A-Za-z0-9]/i+').click()

Reason - The web page that I'm trying to automate has these classes generated dynamically using the ant-design framework , which keeps changing after some time and makes it hard to generate locators.

Please excuse if the regex pattern is not correct.

aslushnikov commented 1 year ago

@zac11 you can probably (ab)use xpath for this (like in this SO question).

I'll check with the folks if there's some nicer way to do this.

zac11 commented 1 year ago

@aslushnikov Playwright has spoiled me in ways that I don't want to use xpath anymore 😆 I'll wait if there is anything we can do with the regex pattern in css locators.

Xpaths are always a last resort ( no offense xpath)

aslushnikov commented 1 year ago

@zac11 you can also use the CSS attribute selectors:

page.locator('css=[class^=testBanner]');

But this is probably the best we can think of!