Search code examples
c#webautomationplaywrightplaywright-sharp

Not able to select an option from drop down selection in Playwright?


I'm trying to fill in an online account creation form. But there is a drop down option thats not a normal select element. Please help sorry if its something easy am new to c#.

public static async Task Main()
    {
        using var playwright = await Playwright.CreateAsync();
        var chromium = playwright.Chromium;
        var browser = await chromium.LaunchAsync(new BrowserTypeLaunchOptions {Headless = false}); 
        
        Console.WriteLine(browser.IsConnected);
        var page = await browser.NewPageAsync();
        await page.GotoAsync("https://www.slamjam.com/en_SG/login?action=register");
        await page.SelectOptionAsync("xpath=/html/body/div[1]/main/div/div/div/div/form/div[1]/span/span[1]/span", new SelectOptionValue { Label = "Mr." });
        await page.FillAsync("id=registration-form-fname", "belinda");
        await page.FillAsync("id=registration-form-lname", "Yeo");
        await page.FillAsync("id=registration-form-birthday", "17/12/1990");
        await page.FillAsync("id=registration-form-email", "email");
        await page.FillAsync("id=registration-form-email-confirm", "email");
        await page.FillAsync("id=registration-form-password", "PW");
        await page.FillAsync("id=registration-form-password-confirm", "PW");
        await page.CheckAsync("xpath=/ html / body / div[1] / main / div / div / div / div / form / div[9] / label");
        await page.CheckAsync("xpath=/html/body/div[1]/main/div/div/div/div/form/div[11]/label");
        await page.ClickAsync("id=validationCaptchaRegistration");
    }

If you see I tried using the select option function in Playwright but to no avail.

Here is the site https://www.slamjam.com/en_SG/login?action=register


Solution

  • As per Max's comment, the issue is that the select element isn't actually a normal HTML select element. It's just a span that displays the list of options underneath it when clicked.

    You can do something like this:

    await page.ClickAsync("id=select2-registration-form-title-container");
    await page.ClickAsync("li:has-text('Mr.'):visible");
    

    Only use IDs if you're fairly sure they won't be changing. Normally, it's best to use attributes that are visible to the user as they're less likely to change.