有关鼠标的操作,不单单只有单击,有时候还要用到右击,双击,拖动等操作,这些操作包含在ActionChains 类中。
首先,导入ActionChains类:
ActionChains 类鼠标操作的常用方法:
- context_click(元素A) :右击元素A
- double_click(元素A) :双击元素A
- drag_and_drop(元素A) :拖动元素A
- move_to_element(元素A) :鼠标移动到元素A上
- click_and_hold(元素A) :按下鼠标左键在元素A上
下面举例说明这些操作在代码中的是如何使用的:
from selenium.webdriver.common.action_chains import ActionChains
# 双击
double = driver.find_element_by_xpath("elementA")
ActionChains(driver).double_click(double).perform()
# 右击
right = driver.find_element_by_xpath("elementB")
ActionChains(driver).context_click(right).perform()
# 拖动
source = driver.find_element_by_xpath('elementC')
target = driver.find_element_by_xpath('elementD')
ActionChains(driver).drag_and_drop(source, target).perform()
# 移动
above = driver.find_element_by_xpath('elementE')
ActionChains(driver).move_to_element(above).perform()
# 单击hold住
left_hold = driver.find_element_by_xpath('elementF')
ActionChains(driver).click_and_hold(left_hold).perform()
首先,导入ActionChains类:
from selenium.webdriver.common.action_chains import ActionChains
其次,定位到你要操作的元素;
接着,执行想要进行的操作:实例化一个actionchains 对像,用于存储对元素的操作行为,最后通过perform来执行操作。