Add keyboard class and Element.press() #1295
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR implements
browser.keyboardandelement.press(). These act as keyboard-specific APIs for using modifier keys so users do not need to use Selenium's ActionChains API directly. It addresses the issues raised in #572.As a downside to the input method, it may lead to typos such as:
browser.keyboard.press("CONTROLx")instead ofbrowser.keyboard.press("CONTROL+x")However, the following is valid and safer, if clunky:
browser.keyboard.press(selenium.Keys.CONTROL)browser.keyboard.press(f"{selenium.Keys.CONTROL}+x")An alternative implementation could use a list instead:
browser.keyboard.press(["CONTROL", "x"])andbrowser.keyboard.press([selenium.Keys.CONTROL, "x"])The inspiration for this design comes from: https://playwright.dev/python/docs/input#keys-and-shortcuts
Sending an arbitrary number of arguments is something I don't favour. It makes type checking more difficult and the code more brittle.
A list is less ambiguous and more difficult to typo. However, the "foo+bar" pattern makes it clearer that
press("CONTROL+a")will do:CONTROL down, a down, CONTROL up, a upand notCONTROL down, CONTROL up, a down, a up@fsouza I'm not 100% done testing and documenting this feature, but it more or less works. Opening the floor to discuss the implementation here before merging.