简体   繁体   English

Puppeteer:如何提交表单?

[英]Puppeteer: How to submit a form?

Using puppeteer , how could you programmatically submit a form?使用puppeteer ,您如何以编程方式提交表单? So far I've been able to do this using page.click('.input[type="submit"]') if the form actually includes a submit input.到目前为止,如果表单实际上包含提交输入,我已经能够使用page.click('.input[type="submit"]')执行此操作。 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:但是对于不包含提交输入的 forms 来说,专注于表单文本输入元素并使用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();

})();

Try this 试试这个

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

For v0.11.0 and laters: 对于v0.11.0和laters:

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

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());

I was scraping a SPA, and I had to use waitForNetworkIdle since the form submit was not triggering a page navigation event.我正在抓取一个 SPA,我不得不使用waitForNetworkIdle ,因为表单提交没有触发页面导航事件。 Instead it submitted data to the server, and updated the DOM of the page which was already loaded.相反,它向服务器提交数据,并更新已加载页面的 DOM。

const [response] = await Promise.all([        
    page.waitForNetworkIdle(),
    page.click('#form-submit-button'),
]);

When to use waitForNetworkIdle何时使用waitForNetworkIdle

I suspect that if you open a normal web browser, submit the form, and look to see if the page URL has changed or not.我怀疑如果你打开一个普通的web浏览器,提交表单,看看页面URL有没有变化。 If it has not changed, you should use waitForNetworkIdle .如果它没有改变,你应该使用waitForNetworkIdle

Also, take this advice with a grain of salt, I've only been using puppeteer for an hour.另外,对这个建议持保留态度,我只使用 puppeteer 一个小时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM