在 python 的 selenium 裡全選後,輸入內容的用法如下:
builder = ActionChains(driver)
builder.move_to_element(el_text)
builder.click(el_text)
if platform.system() == 'Darwin':
builder.key_down(Keys.COMMAND)
else:
builder.key_down(Keys.CONTROL)
builder.send_keys("a")
if platform.system() == 'Darwin':
builder.key_up(Keys.COMMAND)
else:
builder.key_up(Keys.CONTROL)
builder.send_keys(val)
if submit:
builder.send_keys(Keys.ENTER)
builder.perform()
在 selenium 裡有 web element 程式碼在:
py/selenium/webdriver/remote/webelement.py
source code:
def send_keys(self, *value) -> None:
"""Simulates typing into the element.
:Args:
- value - A string for typing, or setting form fields. For setting
file inputs, this could be a local file path.
Use this to send simple key events or to fill out form fields::
form_textfield = driver.find_element(By.NAME, 'username')
form_textfield.send_keys("admin")
This can also be used to set file inputs.
::
file_input = driver.find_element(By.NAME, 'profilePic')
file_input.send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
"""
# transfer file to another machine only if remote driver is used
# the same behaviour as for java binding
if self.parent._is_remote:
local_files = list(
map(
lambda keys_to_send: self.parent.file_detector.is_local_file(str(keys_to_send)),
"".join(map(str, value)).split("\n"),
)
)
if None not in local_files:
remote_files = []
for file in local_files:
remote_files.append(self._upload(file))
value = "\n".join(remote_files)
self._execute(
Command.SEND_KEYS_TO_ELEMENT, {"text": "".join(keys_to_typing(value)), "value": keys_to_typing(value)}
)
網路上流傳的古時候的錯誤用法1:
src_elem.click()
src_elem.send_keys(Keys.CONTROL, 'a') # select all the text
src_elem.send_keys(Keys.CONTROL, 'c') # copy it
網路上流傳的古時候的錯誤用法2:
String selectAll = Keys.chord(Keys.CONTROL, "a");
element.sendKeys(selectAll);
或
Try to chord the Ctrl+A keys. The code below is working in my case:
element.sendKeys(Keys.chord(Keys.CONTROL, "a"));
以上3個, 是錯誤示範, 會顯示 chord 並不存在。