如何在contenteditable文本框中模拟“回车”键盘事件

2024-04-18 21:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python中使用selenium访问一个文本框来执行javascript。我正在成功键入消息,但需要模拟“回车”键盘事件来提交消息。我是HTML和Javascript的绝对初学者,但据我所知,textbox没有输入id,只有一个内容可编辑的文本字段,这可能会导致问题。你知道吗

以前,我尝试使用selenium通过其id、xpath和类名并使用send\u键来访问textbox元素。这不起作用,因为我得到了一个'元素无法通过键盘'的错误。现在,我尝试在浏览器(firefox)中直接执行javascript。发送“你好,世界!”通过编辑p-tag部分的内部html来工作,但是我不能按enter键。到目前为止,我已经尝试将dispatchEvent与以下代码一起使用,它不会在浏览器控制台中显示任何错误,但不会输入消息。你知道吗

driver.execute_script("document.querySelector('#msg_input > div:nth-child(1) > p:nth-child(1)').innerHTML = '" + "hello world!" + "'") #this line works        

driver.execute_script("""
                      const keyEnterEvent = new KeyboardEvent('keyboard', {
                          bubbles: true, cancelable: true, keyCode: 13
                      });
                      document.querySelector('#msg_input > div:nth-child(1) > p:nth-child(1)').dispatchEvent(keyEnterEvent);
""") #this part does not work

我希望得到这个或类似的方法模拟输入键工作,任何帮助将不胜感激!你知道吗


Tags: idchild消息元素编辑executedriverselenium
1条回答
网友
1楼 · 发布于 2024-04-18 21:36:12

我刚刚在Mozilla docs(https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable)上测试了“contenteditable”元素,似乎可以通过单击该元素,键入,然后从中跳出来进行编辑(而不是根据您的示例按Enter)。你知道吗

如果您不是在无头浏览器中运行自动化,我会通过查找元素的X,Y坐标,用类似AppRobotic的宏功能来模拟:

import win32com.client
x = win32com.client.Dispatch("AppRobotic.API")
from selenium import webdriver

# navigate to Google
driver = webdriver.Firefox()
driver.get('https://www.google.com') 

# use UI Item Explorer tool to find the X,Y coordinates of Search box
x.MoveCursor(438, 435)
# click inside Search box
x.MouseLeftClick

x.Type("hello world!")
x.Type("{TAB}")
x.Type("{ENTER}")

相关问题 更多 >