For Puppeteer Sharp, the syntax is a little different, and there are 2 ways to do it, but one is better than the other. Here is a full example:
static async Task Main(string[] args)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
await using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Product = Product.Chrome }))
await using (var page = await browser.NewPageAsync())
{
try
{
await page.GoToAsync(urlString);
await page.WaitForSelectorAsync("#btnSubmit");
await ReplaceText(page, "#inputUsernameId", usernameString);
await ReplaceText(page, "#inputPasswordId", passwordString);
await page.ClickAsync("#btnSubmit");
await page.WaitForNavigationAsync(); // Optional, if the page is changing
}
catch (Exception ex)
{
Console.WriteLine(ex);
// Handle me / Log me
throw;
}
}
}
private static async Task ReplaceText(Page page, string selector, string replacementValue)
{
await page.WaitForSelectorAsync(selector).ConfigureAwait(false);
await page.EvaluateExpressionAsync($"document.querySelector(\"{selector}\").value = \"{replacementValue}\"").ConfigureAwait(false);
// Alternative older method below (not as reliable with async, but works):
// await ele.FocusAsync().ConfigureAwait(false);
//
// await page.Keyboard.DownAsync("Control").ConfigureAwait(false);
// await ele.PressAsync("A").ConfigureAwait(false);
// await page.Keyboard.UpAsync("Control").ConfigureAwait(false);
// await ele.PressAsync("Backspace").ConfigureAwait(false);
//
// await ele.TypeAsync(replacementText).ConfigureAwait(false);
// await ele.PressAsync("Tab").ConfigureAwait(false);
}