Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SeleniumHQ
GitHub Repository: SeleniumHQ/Selenium
Path: blob/trunk/py/selenium/webdriver/common/actions/key_actions.py
4049 views
1
# Licensed to the Software Freedom Conservancy (SFC) under one
2
# or more contributor license agreements. See the NOTICE file
3
# distributed with this work for additional information
4
# regarding copyright ownership. The SFC licenses this file
5
# to you under the Apache License, Version 2.0 (the
6
# "License"); you may not use this file except in compliance
7
# with the License. You may obtain a copy of the License at
8
#
9
# http://www.apache.org/licenses/LICENSE-2.0
10
#
11
# Unless required by applicable law or agreed to in writing,
12
# software distributed under the License is distributed on an
13
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
# KIND, either express or implied. See the License for the
15
# specific language governing permissions and limitations
16
# under the License.
17
18
from __future__ import annotations
19
20
from selenium.webdriver.common.actions.interaction import KEY, Interaction
21
from selenium.webdriver.common.actions.key_input import KeyInput
22
from selenium.webdriver.common.actions.pointer_input import PointerInput
23
from selenium.webdriver.common.actions.wheel_input import WheelInput
24
from selenium.webdriver.common.utils import keys_to_typing
25
26
27
class KeyActions(Interaction):
28
def __init__(self, source: KeyInput | PointerInput | WheelInput | None = None) -> None:
29
if source is None:
30
source = KeyInput(KEY)
31
self.input_source = source
32
super().__init__(source)
33
34
def key_down(self, letter: str) -> KeyActions:
35
return self._key_action("create_key_down", letter)
36
37
def key_up(self, letter: str) -> KeyActions:
38
return self._key_action("create_key_up", letter)
39
40
def pause(self, duration: int = 0) -> KeyActions:
41
return self._key_action("create_pause", duration)
42
43
def send_keys(self, text: str | list) -> KeyActions:
44
if not isinstance(text, list):
45
text = keys_to_typing(text)
46
for letter in text:
47
self.key_down(letter)
48
self.key_up(letter)
49
return self
50
51
def _key_action(self, action: str, letter) -> KeyActions:
52
meth = getattr(self.source, action)
53
meth(letter)
54
return self
55
56