This might be a trivial question/answer, however I would like to know if there is a way that I could store an element locator in a variable and then reuse it same as it while working with Selenium and Page Object Pattern.

In my previous work I used to write automation test in Visual Studio and I used Selenium Web-driver along with Page Object Pattern approach. During my work on the Page Objects and later component, I could declare all selectors by FindBy annotation and then reuse it for the purpose of future tests. I have just started my adventure with Playwright and I was wondering if I could achieve same approach. So far all examples in web showed that each time when you have an element selector you perform already an action on it.

Lets say that I have a Page Object Class called "Home Page". On this page there is a "Submit" button. I would like to get location of this button and store in a variable so I can reuse it in the future. How can I achieve similar out which I used with FindBy annotation?

So instead of having common approach such as -> await page.click('button'); I would like to have something which will look like this -> const submitButton= [location of button tag];

Thanks in advance for any guidance.

1 Answer 1

    const playwright = require('playwright');
    (async () => {
        const browser = await playwright["chromium"].launch({ headless: false});
        const context = await browser.newContext();
        const page = await context.newPage();
        await page.goto('http://www.google.com/');
        await page.screenshot({ path: `example-chromium.png` });
        locator = '[name="q"]'
        await page.fill(locator,"hiiiii")

what stops you from storing element locator in a variable ?

  • 2
    PDHide I think that because of me being new to Playwright and JS and the materials which I saw of not having such simple examples. Thanks for providing an answer, however just one more thing if I may. Should I declare variables which will be storing element locators as const or let? Thanks! Apr 14, 2021 at 19:13
  • @Automation_Padawan constant makes more sence as the locator is not going to change during run time. But using let or const doesn't affect the run in any way
    – PDHide
    Apr 14, 2021 at 21:42
  • Locator do change properties based on events in UI. May 4, 2021 at 1:08
  • @Vishal constant is about the variable not the locator ,we don't modify the variable value on the run
    – PDHide
    May 4, 2021 at 5:24
  • Locator is just an string value of the variable which can change at runtime. May 5, 2021 at 1:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.