3

如何提交表格?我有一个简单的搜索栏和一个搜索按钮。下面输入搜索字符串,但不触发click事件。当 headless 设置为 false 并且我在 serachfield 中手动单击 enter 时,搜索正在工作。如何提交按钮?

  const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('http://localhost:3000', {waitUntil: 'networkidle'});

await page.focus('#search');

// Type our query into the search bar
await page.type('michael');

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

await page.screenshot({path: './screenshots/search3.png'});

browser.close();
})();

我的搜索栏

search(e) {
 e.preventDefault();
this.props.onClick(this.props.value);}

render() {
return (<form className="form-inline" id="search-form" onSubmit
{this.search}>
  <div className="form-group">
    <input
      type="text"
      className="form-control"
      id="search"
      value={this.props.value}
      placeholder={this.props.placeHolder}
      onChange={this.props.onChange}
    />

    <button primary type="submit" >
      {this.props.buttonText}
    </button>
  </div>
</form>);
}

更新

这不起作用:

const searchForm = await page.$('#search-form'); 
await searchForm.evaluate(searchForm => searchForm.submit()); 

它执行回发并且表单中的文本被清除,即使它应该使用 preventDefault 触发该函数。

所以问题似乎是这行代码等待

searchForm.evaluate(searchForm => searchForm.submit());

这是有效的:

我将代码更改为:

await page.click('#search-button'); 
await page.waitForNavigation(); 
4

4 回答 4

9

我通过使用它而不是提交表单来解决它:

await page.click('#search-button'); 
await page.waitForNavigation(); 
于 2017-10-19T08:01:57.413 回答
2

您可以通过发送以下方式提交表格:
await page.click("button[type=submit]");

在这里找到:https ://stackoverflow.com/a/46965168/8839237

于 2021-05-28T17:17:11.427 回答
0

假设您的搜索栏的 ID 为“搜索”,

基本上,您需要使用选择器表达式来获取搜索栏的句柄,然后使用该evaluate功能可以进行表单提交,

您需要有以下代码段才能提交您的表单,

const searchForm = await page.$('#search');
await searchForm.evaluate(searchForm => searchForm.submit());

希望这可以帮助

于 2017-09-13T07:35:20.167 回答
0

首先点击这个链接

puppeteer-how-to-submit-a-form

你的问题

当你按下回车而不是截图时,这就是问题。

// this code just await press event finished, but not form submitted finished,
//in this way, you can not screenshot form submit finished status
await page.press('Enter'); 
await page.screenshot({path: './screenshots/search3.png'});
// form submitting ...

这就是您的代码不起作用的原因。

希望能帮到你

于 2017-09-27T13:01:38.587 回答