一、ActionChains包
模擬鼠標的操作要首先引入ActionChains的包
from selenium.webdriver.common.action_chains import ActionChains
而對於ActionChains包,一般的寫法是:

這是這個方法一般的書寫格式,下面我們來看一如何使用模擬鼠標操作的具體案例
1.鼠標拖動操作
方法:
drag_and_drop(source, target)
拖動source元素到target元素的位置
drag_and_drop_by_offset(source, xoffset, yoffset)
source:鼠標拖動的原始元素
xoffset:鼠標把元素拖動到另外一個位置的x坐標
yoffset:鼠標把元素拖動到另外一個位置的y坐標
拖動source元素到指定的坐標
————————————————
版權聲明:本文為CSDN博主「許西城」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/ccggaag/article/details/75717186
二、代碼示例
測試網址:https://jqueryui.com/resources/demos/draggable/scroll.html

# coding=UTF-8 #17.拖拽頁面元素 import sys reload(sys) sys.setdefaultencoding('utf8') from selenium import webdriver import unittest import time from selenium.webdriver import ActionChains class Case17(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() def test_dragPageElement(self): url = "https://jqueryui.com/resources/demos/draggable/scroll.html" self.driver.get(url) position1 = self.driver.find_element_by_id("draggable") position2 = self.driver.find_element_by_id("draggable2") position3 = self.driver.find_element_by_id("draggable3") ActionChains(self.driver).drag_and_drop(position1,position2).perform() #把position1拖到position2的位置 time.sleep(2) ActionChains(self.driver).drag_and_drop_by_offset(position3,10,10).perform() #把position3拖動(10,10)的距離,即向右下方拖動 time.sleep(2) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
