Javascript Puppeteer:如何提交表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45778181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:12:48  来源:igfitidea点击:

Puppeteer: How to submit a form?

javascriptnode.jsgoogle-chrome-headlesspuppeteer

提问by docta_faustus

Using puppeteer, how could you programmatically submit a form? So far I've been able to do this using page.click('.input[type="submit"]')if the form actually includes a submit input. But for forms that don't include a submit input, focusing on the form text input element and using page.press('Enter')doesn't seem to actually cause the form to submit:

使用puppeteer,您如何以编程方式提交表单?到目前为止,page.click('.input[type="submit"]')如果表单实际上包含提交输入,我已经能够做到这一点。但是对于不包含提交输入的表单,关注表单文本输入元素并使用page.press('Enter')似乎并没有真正导致表单提交:

const puppeteer = require('puppeteer');

(async() => {

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://stackoverflow.com/', {waitUntil: 'load'});
    console.log(page.url());

    // Type our query into the search bar
    await page.focus('.js-search-field');
    await page.type('puppeteer');

    // Submit form
    await page.press('Enter');

    // Wait for search results page to load
    await page.waitForNavigation({waitUntil: 'load'});


    console.log('FOUND!', page.url());

    // Extract the results from the page
    const links = await page.evaluate(() => {
      const anchors = Array.from(document.querySelectorAll('.result-link a'));
      return anchors.map(anchor => anchor.textContent);
    });
    console.log(links.join('\n'));
    browser.close();

})();

回答by Grant Miller

If you are attempting to fill out and submit a login form, you can use the following:

如果您尝试填写并提交登录表单,您可以使用以下方法:

await page.goto('https://www.example.com/login');

await page.type('#username', 'username');
await page.type('#password', 'password');

await page.click('#submit');

await page.waitForNavigation();

console.log('New Page URL:', page.url());

回答by Nam Mai Anh

Try this

尝试这个

const form = await page.$('form-selector');
await form.evaluate(form => form.submit());


For v0.11.0 and laters:

对于 v0.11.0 及更高版本:

await page.$eval('form-selector', form => form.submit());