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
1864 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 ..utils import keys_to_typing
21
from .interaction import KEY, POINTER, WHEEL, Interaction
22
from .key_input import KeyInput
23
from .pointer_input import PointerInput
24
from .wheel_input import WheelInput
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
33
# Determine the correct source type string based on the input object
34
if isinstance(source, KeyInput):
35
source_type = KEY
36
elif isinstance(source, PointerInput):
37
source_type = POINTER
38
elif isinstance(source, WheelInput):
39
source_type = WHEEL
40
else:
41
source_type = KEY
42
43
super().__init__(source_type)
44
45
def key_down(self, letter: str) -> KeyActions:
46
return self._key_action("create_key_down", letter)
47
48
def key_up(self, letter: str) -> KeyActions:
49
return self._key_action("create_key_up", letter)
50
51
def pause(self, duration: int = 0) -> KeyActions:
52
return self._key_action("create_pause", duration)
53
54
def send_keys(self, text: str | list) -> KeyActions:
55
if not isinstance(text, list):
56
text = keys_to_typing(text)
57
for letter in text:
58
self.key_down(letter)
59
self.key_up(letter)
60
return self
61
62
def _key_action(self, action: str, letter) -> KeyActions:
63
meth = getattr(self.input_source, action)
64
meth(letter)
65
return self
66
67