Pressing Enter button in puppeteer

北城余情 提交于 2019-12-18 12:09:35

问题


Pressing enter in puppeteer doesn't seem to have any effect. However, when I press other keys, it does what it should. This works:

await page.press('ArrowLeft');

This doesn't:

await page.press('Enter');

This is how the input looks like:

Any ideas?

EDIT: I've also tried page.keyboard.down & page.keyboard.up to be sure.


回答1:


await page.type(String.fromCharCode(13));

Using this site I noticed that page.type dispatches beforeinput and input events, but page.press doesn't. This is probably a bug, but fortunately sending the enter keycode (13) seems to work, so we can work around it for now.




回答2:


I've used page.keyboard.press('Enter'); usually :) Works for me.

Have a look at the documentation here. I think you should use .keyboard before .press for it to work properly.




回答3:


page.keyboard.press():

You can use page.keyboard.press() to simulate pressing the enter key. Any of the following options should work:

await page.keyboard.press('Enter'); // Enter Key
await page.keyboard.press('NumpadEnter'); // Numeric Keypad Enter Key
await page.keyboard.press('\n'); // Shortcut for Enter Key
await page.keyboard.press('\r'); // Shortcut for Enter Key

elementHandle.press():

Additionally, you can use use a combination of page.$() and elementHandle.press() to focus on an element before pressing enter:

await (await page.$('input[type="text"]')).press('Enter'); // Enter Key
await (await page.$('input[type="text"]')).press('NumpadEnter'); // Numeric Keypad Enter Key
await (await page.$('input[type="text"]')).press('\n'); // Shortcut for Enter Key
await (await page.$('input[type="text"]')).press('\r'); // Shortcut for Enter Key

page.type():

Furthermore, you can use page.type():

await page.type(String.fromCharCode(13));

page.keyboard.type():

Likewise, you can use page.keyboard.type():

await page.keyboard.type(String.fromCharCode(13));

page.keyboard.sendCharacter():

Another alternative method would be to use the page.keyboard.sendCharacter() method:

await page.keyboard.sendCharacter(String.fromCharCode(13));

page.keyboard.down() / page.keyboard.up():

You can also use a combination of page.keyboard.down() and page.keyboard.up():

// Enter Key
await page.keyboard.down('Enter');
await page.keyboard.up('Enter');

// Shortcut for Enter Key
await page.keyboard.down('NumpadEnter');
await page.keyboard.up('NumpadEnter');

// Shortcut for Enter Key
await page.keyboard.down('\n');
await page.keyboard.up('\n');

// Shortcut for Enter Key
await page.keyboard.down('\r');
await page.keyboard.up('\r');


来源:https://stackoverflow.com/questions/46442253/pressing-enter-button-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!