Search code examples
typescriptplaywright

How to detect if captcha is visible on playwright?


New to playwright and I'm practicing assertions. On this site, there is a visible captcha element and I can find it using frameLocator. The display is none. I'M NOT TRYING TO SOLVE IT, I just want to log that I've found it. When I use toBeVisible() it runs into an error saying "Expected: visible Received: hidden". Without using toBeHidden() how can I check that this is visible on the page? Here is the code below.

import { test, expect } from '@playwright/test';
import { describe } from 'node:test';


describe("Check if Captcha", () => {

  test('findCaptcha', async ({ page }) => {

    // go to this search
    await page.goto("https://www.google.com/search?q=captcha+demo&sca_esv=595089826&ei=ORmUZfDvBteo5NoP6OW5iAQ&ved=0ahUKEwiw8P7u8L6DAxVXFFkFHehyDkEQ4dUDCBA&uact=5&oq=captcha+demo&gs_lp=Egxnd3Mtd2l6LXNlcnAiDGNhcHRjaGEgZGVtbzILEAAYgAQYigUYkQIyBxAAGIAEGAoyBxAAGIAEGAoyBhAAGBYYHjIGEAAYFhgeMgYQABgWGB4yBhAAGBYYHjIGEAAYFhgeMgYQABgWGB4yBhAAGBYYHkjfJlCTBFivI3ACeAGQAQCYAWqgAdUEqgEDMy4zuAEDyAEA-AEBwgIKEAAYRxjWBBiwA8ICDRAAGIAEGIoFGEMYsAPCAg0QABiABBiKBRhDGLEDwgIKEAAYgAQYigUYQ8ICBRAAGIAEwgIQEAAYgAQYigUYkQIYRhj5AcICJxAAGIAEGIoFGJECGEYY-QEYlwUYjAUY3QQYRhj0Axj1Axj2A9gBAcICCBAAGBYYHhgK4gMEGAAgQYgGAZAGCroGBggBEAEYEw&sclient=gws-wiz-serp")

    // click googles first result
    await page.getByRole('link', { name: 'ReCAPTCHA demo Google https://www.google.com › recaptcha › api2 › demo' }).click();

    const captchaText = page.frameLocator('iframe[name="a-wzwqbw7k5wb7"]').getByText('I\'m not a robot');


    // expect captcha to be visible
    await expect(captchaText).toBeVisible();
  });
})

I tried to wait for network responses when clicking it and although it worked, it threw an error in a situation where the captcha wasn't visible (It continued to try to make request and crashed when I gave it a timeout)


Solution

  • Iframe may have a different name each time - use the title instead

    import { test, expect } from "@playwright/test";
    
    test("https://stackoverflow.com/questions/77746853", async ({ page }) => {
        await page.goto("https://www.google.com/recaptcha/api2/demo");
        const frame = page.frameLocator("iframe[title='reCAPTCHA']");
        const label = frame.locator("#recaptcha-anchor-label");
        await expect(label).toHaveText("I'm not a robot");
    });