selenium python (三)鼠标事件

时间:2024-07-09 10:33:26

# -*- coding: utf-8 -*-
#鼠标事件

#ActionChains类中包括:

                      # context_click()  右击;
                        # double_click() 双击;
                        # drag_and_drop() 拖动;
                        # move_to_element()鼠标悬停在一个元素上;
#首先引入ActionChains

from selenium.webdriver.common.action_chains import ActionChains
from selenium import webdriver
driver = webdriver.Firefox()

driver.get('http://www.baidu.com')

#定位到要操作的元素
target_element = driver.find_element_by_id('xx')
#执行ActionChains中存储的行为,需要用perform()
#右击元素
ActionChains(driver).context_click(target_element).perform()

#双击元素
ActionChains(driver).double_click(target_element).perform()

#拖动元素drag_and_drop(source,target)
source = driver.find_element_by_id('xx')
target = driver.find_element_by_id('yy')
ActionChains(driver).drag_and_drop(source,target).perform()

#鼠标悬停在一个元素上
ActionChains(driver).move_to_element(target_element).perform()