Selenium 如何完成 Drag & Drop 動作
這篇文章主要用一個範例說明如何用 Selenium 模擬滑鼠的Drag & Drop的動作。
範例網站
http://jqueryui.com/resources/demos/droppable/default.html
首先先觀察這兩個元件,
Source draggable 的 ID 為 “draggable”。因此在 Selenium程式中,就可以定義
source = driver.find_element_by_id("draggable")
Destination drop here 的 ID 為”droppable”。Selenium 程式中,定義
target = driver.find_element_by_id("droppable")
定義source and target 之後,接著要完成的就是 drag and drop.
將 source and target 帶入 actionChain.drop_and_drop參數,即可
ActionChains(self.driver).drag_and_drop(source, target).perform()
最後,drop 完之後,droppable Text 會出現 Dropped ! 可以用此驗證是否成功 drag and drop.
self.assertEqual("Dropped!", target.text)
完整程式碼範例
[pastacode lang=”python” message=”Selenium Drag and Drop Sample” highlight=”” provider=”manual”]
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import unittest
class DragAndDropTest (unittest.TestCase):
URL = "http://jqueryui.com/resources/demos/droppable/default.html"
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get(self.URL)
self.driver.implicitly_wait(30)
self.driver.maximize_window()
def test_drag_and_drop(self):
driver = self.driver
source = driver.find_element_by_id("draggable")
target = driver.find_element_by_id("droppable")
ActionChains(self.driver).drag_and_drop(source, target).perform()
self.assertEqual("Dropped!", target.text)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main(verbosity=2)
[/pastacode]