[selenium] Simulate right click.

Selenium works on web elements, so any browser’s function selenium cannot automate. On this exercise, right click within the dotted box area will trigger a JS alert which says “You selected a context menu”. To simulate right click with Selenium:

First find the element of the dotted box, then use ActionChains to move to the dotted box’s element, then use context_click method finally use perform method to execute the chain.

Second wait for the alert to appear, once it appears, switch the focus from the main page to the alert box, then use accept method to click on OK button.

There is a catch, the right click simulation will also trigger browser’s option which selenium cannot manipulate.

This is the original state.
This is the state after selenium simulates right click then click ok to dismiss the alert.

The code for the solution is as below:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as condition

import os
from time import sleep


def find_file(base="C:\\", name=None):
    """
    Find file and return the first match found.
    :param base: Base path to search
    :param name: filename to search
    :return: absolute path of the file.
    """
    for root, dirs, filename in os.walk(base):
        if name in filename:
            return os.path.join(root, name)


driver = webdriver.Firefox(executable_path=find_file(name="geckodriver.exe"))
driver.get('https://the-internet.herokuapp.com/context_menu')
dotted_box = driver.find_element_by_xpath('//*[@id="hot-spot"]')

# Move to the dotted box and do a right click.
ActionChains(driver).move_to_element(dotted_box).context_click().perform()

# This means the driver will wait for a maximum 20 seconds for the alert to appear.
# The wait is over if the alert appears, hence this is not the same as time.sleep(20).
WebDriverWait(driver, 20).until(condition.alert_is_present())

# switch to the JS alert.
alert = driver.switch_to.alert
sleep(10)

# this clicks OK.
alert.accept()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s