2017-09-13 59 views
0

如何提交表格? 我有一个简单的搜索栏和一个搜索按钮。以下内容输入搜索字符串,但点击事件未被触发。当无头被设置为假,并且我手工点击进入serachfield时,搜索正在工作。如何提交按钮?木偶 - 如何提交表格

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

UPDATE

这不是工作:

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

它不回发,并在表单中的文本被清除,即使它sh用preventDefault触发该功能。

所以这个问题似乎是这行代码伺机

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

这是工作:

我改变了代码:

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

截图看看怎么样,如果这个问题没有解决。请考虑附加它。 –

回答

2

我解决它用这个代替的提交形式:

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

假设你的搜索栏有“搜索”作为它的ID,

基本上你还是d使用选择表达式得到一个处理你的搜索栏,然后使用evaluate功能,你可以做表单提交,

你需要有下面的代码片段提交表单,

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

希望这有助于

+0

好了,现在窗体被触发了,但是我的onSubmit函数没有被使用。我已将表单代码添加到问题中。 提交表单时,搜索字符串消失,我的网址变为 'localhost:3000 /?'。 手动执行搜索字符串存储在搜索字段中,url变成 'localhost:3000 /?searchString = michael' – Kristoffer

+0

@Kristoffer您是否尝试添加我的建议?(或)您的代码现在开始工作? –

+0

我增加了你的建议,现在puppeteer似乎在运行(不会中断),但是我没有得到预期的输出结果。它似乎没有触发正确的onSubmit功能。 – Kristoffer

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 ... 

这就是为什么你的代码不工作。

希望能帮助您

+0

问题不在屏幕截图中,而是提交表单。如果我禁用了屏幕截图,它仍然没有提交正确的表单。 我试图运行它没有无头,所以我可以看到,即使在截图后,表格还没有正确提交。 – Kristoffer