ActionChains.context_click(element).perform()ActionChains(driver).context_click(el).perform()# 快速参考 from selenium.webdriver.common.action_chains import ActionChains btn = driver.find_element(By.ID, "p2_btn") ActionChains(driver).context_click(btn).perform()
操作步骤:
① 用 driver.find_element(By.ID, "p2_btn") 定位「在此处右击」按钮;
② 调用 ActionChains(driver).context_click(btn).perform() 执行右击;
③ 断言 p2_menu 菜单元素可见,或 p2_result 包含「右键菜单已弹出」。
💡 提示:Selenium 中通过 ActionChains(driver).context_click(btn).perform() 触发右击,contextmenu 事件会被 JS 拦截并弹出自定义菜单。
# 练习 2 参考答案 · 右击 from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains driver.get("https://autotest-505.pages.dev/mouse_op_practice.html") btn = driver.find_element(By.ID, "p2_btn") actions = ActionChains(driver) # 在元素上右击 actions.context_click(btn).perform() # 断言菜单可见 menu = driver.find_element(By.ID, "p2_menu") assert menu.is_displayed()