Search code examples
c#xpathweb-scrapingpuppeteerpuppeteer-sharp

Cannot click on a button which have a specific attribute


I'm using puppeteer-sharp for get content loaded by AJAX from a web page. I need to submit a form which have the following structure:

<form action="" method="post" _lpchecked="1">
    <div class="item">
        <div class="title"><label for="login-username1">Username</label></div>
        <div>
            <input class="int-text" type="text" id="login-username1" name="login-username" value="" size="25" autocomplete="off" >
            <span class="required" title="required item">*</span>
        </div>
    </div>
    <div class="item">
        <div class="title"><label for="login-password1">Password</label></div>
        <div>
            <input class="int-text" type="password" id="login-password1" name="login-password" size="25" autocomplete="off">
            <span class="required" title="required item">*</span>
        </div>
    </div>
    <div class="item">
        <button type="submit" name="login-submit" class="inline-btn-2"><span><span>Login</span></span></button>
    </div>
</form>

First, I filled the two inputs available: login-username1 and login-password1, using the following code:

using (Page page = await Browser.NewPageAsync())
{
    await page.GoToAsync("https://www.oddsportal.com/login/");
    await page.TypeAsync("#login-username1", "sfarzoso");
    await page.TypeAsync("#login-password1", "password");

    await page.ClickAsync("name=login-submit");
    await page.WaitForNavigationAsync();
    var c = await page.GetContentAsync();
}

the problem is that the button doesn't have an id but just a name attribute, so my code return:

PuppeteerSharp.EvaluationFailedException: 'Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': 'name=login-submit' is not a valid selector. at puppeteer_evaluation_script:1:33'

this error happen on

await page.ClickAsync("name=login-submit");

the method ClickAsync want a selector, and the button just have a unique name, seems that I'm not able to click on that button though.

NB: Browser variable is instantiated as following:

Browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
    Headless = true,
    ExecutablePath = Environment.GetEnvironmentVariable("CHROME_PATH"),
});

Solution

  • If you are using CSS selector as a locator then you haven't provided correct locator.

    You can try following CSS Selector which should work.

    Using Type attribute

    await page.ClickAsync("button[type='submit']");
    

    OR Using name attribute

     await page.ClickAsync("button[name='login-submit']");
    

    OR using class attribute

    await page.ClickAsync("button.inline-btn-2");
    

    OR Using multiple attribute such as

    await page.ClickAsync("button[type='submit'][name='login-submit']");