【问题标题】:Not able to select an option from drop down selection in Playwright?无法从 Playwright 的下拉选项中选择一个选项?
【发布时间】:2021-11-15 06:23:57
【问题描述】:

我正在尝试填写在线帐户创建表格。但是有一个下拉选项不是普通的选择元素。如果它对 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");
    }

如果您看到我尝试使用 Playwright 中的选择选项功能但无济于事。

这里是网站https://www.slamjam.com/en_SG/login?action=register

【问题讨论】:

  • 该页面上的选择不是本机选择 (<select>),而是自定义选择。因此,在您的情况下,您需要先单击它,然后再单击实际项目。我建议使用 Playwright 的代码生成器,它可以帮助您创建好的选择器:playwright.dev/docs/cli#generate-code

标签: c# webautomation playwright playwright-sharp


【解决方案1】:

根据Max's comment,问题在于select 元素实际上不是普通的HTML select 元素。它只是一个span,单击时会在其下方显示选项列表。

你可以这样做:

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

只有在您确信 ID 不会发生变化时才使用它们。通常是best to use attributes that are visible to the user,因为它们不太可能改变。

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2021-11-26
    • 2016-10-13
    • 1970-01-01
    • 2021-06-16
    • 2015-03-13
    • 2018-12-28
    • 1970-01-01
    相关资源
    最近更新 更多