About this lesson
Selenium Python context_click: right-click a button and read what changed
Selenium Python AssignmentsAdvancedMouse and Keyboard
How it works
A right click is called a context click, because it normally opens a context menu. In Selenium Python the method is ActionChains.context_click. It takes the element to click, and like every action it only runs when the chain ends with .perform().
Notice what is missing. A WebElement has no context_click attribute, so asking for it there raises AttributeError. The gesture belongs to the chain object, never to the element.
This page reacts to the mouse button number, not to a menu. Button 2 going down triggers the text change. If an app draws its own menu in HTML, that menu is made of ordinary elements, and you click its items after the right click.
Steps can be mixed in one chain. A right click followed by a double click on another button ran both, in order. For clarity, keep each gesture in its own chain unless the order itself is what you test.
About the assignment
Print the label of a button, send it a right click, and print the label again so the change shows in your output.
What you will do
- Find the right-click button by its id and read its
.text. Print it after the first label. - Create a chain that context clicks that element, then run it.
- Read the text of the same element again and print it after the second label.
Common mistakes
Using a left click
The ordinary
click()left the text unchanged here. The handler only reacts to the secondary button.Calling the gesture on the element
button.context_clickraisesAttributeError: 'WebElement' object has no attribute 'context_click'. Start fromActionChains(driver).Skipping perform()
The chain exists but no mouse event was sent. The text stays as it was, and no error tells you why.
In a real test suite
In suites, a right click usually opens an app-drawn menu, such as rename or delete on a file list. A page object method performs the gesture and then waits for the menu with WebDriverWait before choosing an item.
Lesson 59 moves from clicks to dragging, where the browser window size starts to matter.
Related lessons
- Double-Click a ButtonDouble click is a sibling gesture with the same chain and read pattern.
- Hover and Read the Color ChangeShows that nothing runs until
perform()is called. - Read Visible TextReads the visible text of an element, as done before and after the click.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/Buttons")
# Right-click #rightClick and print both texts
finally:
driver.quit()