如何使用Puppeteer从输入中删除现有文本? [英] How to delete existing text from input using Puppeteer?

查看:714
本文介绍了如何使用Puppeteer从输入中删除现有文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在包含当前记录标题的可编辑输入中测试修改文本,并且我希望能够测试编辑此类文本,并用其他内容替换.

I'm trying to test amending text in an editable input which contains the title of the current record - and I want to able to test editing such text, replacing it with something else.

我知道我可以使用await page.type('#inputID', 'blah');在文本框中插入"blah"(在我的情况下,该文本具有现有文本,仅附加"blah"),但是,我找不到任何页面方法.

I know I can use await page.type('#inputID', 'blah'); to insert "blah" into the textbox (which in my case, having existing text, only appends "blah"), however, I cannot find any page methods1 that allow deleting or replacing existing text.

推荐答案

您可以根据需要使用page.evaluate来操作DOM:

You can use page.evaluate to manipulate DOM as you see fit:

await page.evaluate( () => document.getElementById("inputID").value = "")

但是,有时仅操作给定的字段可能还不够(目标页面可以是带有事件侦听器的SPA),因此最好模拟真实的按键.下面的示例来自puppeteer的Github中与该任务有关的信息性问题.

However sometimes just manipulating a given field might not be enough (a target page could be an SPA with event listeners), so emulating real keypresses is preferable. The examples below are from the informative issue in puppeteer's Github concerning this task.

在此,我们按Backspace键的次数与该字段中字符的输入次数相同:

Here we press Backspace as many times as there are characters in that field:

const inputValue = await page.$eval('#inputID', el => el.value);
for (let i = 0; i < inputValue.length; i++) {
  await page.keyboard.press('Backspace');
}

另一个有趣的解决方案是单击目标字段3次,以便浏览器将选择其中的所有文本,然后您可以键入所需的内容:

Another interesting solution is to click the target field 3 times so that the browser would select all the text in it and then you could just type what you want:

const input = await page.$('#inputID');
await input.click({ clickCount: 3 })
await input.type("Blah");

这篇关于如何使用Puppeteer从输入中删除现有文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆