简体   繁体   English

使用 javascript python selenium 按键

[英]Key press with javascript python selenium

Is there a way to basically simulate key pressing from a keyboard?有没有办法基本上模拟键盘上的按键?

I want to click an element that's typable and then mimic what an end-user would do to type, by pressing keys.我想单击一个可打字的元素,然后通过按键来模拟最终用户将要输入的内容。 I don't want to give any XPath and then use sendkeys or anything.我不想给任何 XPath 然后使用 sendkeys 或任何东西。

Bascially element.click() -> keypressing, I'm pretty sure selenium has no option for this that's why I'm turning to js.基本上 element.click() -> 按键,我很确定 selenium 对此没有选择,这就是我转向 js 的原因。 Does anyone know if something like this is possible?有谁知道这样的事情是否可能?

EDIT: The test is done on a webpage编辑:测试是在网页上完成的

Can this be done?这能做到吗?

First, you'll need to obtain the element (use XPath or CSS_Selector).首先,您需要获取元素(使用 XPath 或 CSS_Selector)。

You can accomplish this with ActionChains for instance if you want to copy/paste text use CTRL+'c' then CTRL+'v':例如,如果您想使用 CTRL+'c' 然后 CTRL+'v' 复制/粘贴文本,您可以使用ActionChains完成此操作:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

driver.get('http://example.com')
element = driver.find_element_by_xpath('the/xpath')

ActionChains(driver).move_to_element(element).click(element).key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL).perform()

Or you can use ActionChains().send_keys()或者你可以使用ActionChains().send_keys()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM