本節重點:
ActionChains 類
context_click() 右擊
double_click() 雙擊
drag_and_drop() 拖動
測試的產品中有一個操作是右鍵點擊檔案清單會彈出一個捷徑功能表,可以方便的選擇捷徑功能表中的選擇對檔案進行操作(刪除、移動、重新命名),之前學習元素的點擊非常簡單:
driver.find_element_by_id(“xxx”).click()
那麼滑鼠的雙擊、右擊、拖動等是否也是這樣的寫法呢?例如右擊:
driver.find_element_by_id(“xxx”).context_click()
經過運行指令碼得到了下面的錯誤提示:
AttributeError: 'WebElement' object has no attribute 'context_click'
提示右點方法不屬於webelement 對象,通過尋找文檔,發現屬於ActionChains 類,但文檔中沒有具體寫法。這裡要感謝 北京-QC-rabbit 的指點,其實整個python+selenium 學習過程都要感謝 北京-QC-rabbit 的指點。
下面介紹滑鼠右鍵的用法,以快播私人雲端為例:
#coding=utf-8 from selenium import webdriverfrom selenium.webdriver.common.action_chains import ActionChainsimport time driver = webdriver.Firefox()driver.get("http://passport.kuaibo.com/login/?referrer=http%3A%2F%2Fwebcloud.kuaibo.com%2F") #登陸快播私人雲端driver.find_element_by_id("user_name").send_keys("username")driver.find_element_by_id("user_pwd").send_keys("123456")driver.find_element_by_id("dl_an_submit").click()time.sleep(3) #定位到要右擊的元素qqq =driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[3]/table/tbody/tr/td[2]")#對定位到的元素執行滑鼠右鍵操作ActionChains(driver).context_click(qqq).perform() '''#你也可以使用三行的寫法,但我覺得上面兩行寫法更容易理解chain = ActionChains(driver)implement = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[3]/table/tbody/tr/td[2]")chain.context_click(implement).perform()''' time.sleep(3) #休眠3秒driver.close()
這裡需要注意的是,在使用ActionChains 類之前,要先將包引入。
右擊的操作會了,下面的其它方法比葫蘆畫瓢也能寫出來。
滑鼠雙擊的寫法:
#定位到要雙擊的元素qqq =driver.find_element_by_xpath("xxx")#對定位到的元素執行滑鼠雙擊操作ActionChains(driver).double_click(qqq).perform()
滑鼠拖放操作的寫法:
#定位元素的原位置element = driver.find_element_by_name("source")#定位元素要移動到的目標位置target = driver.find_element_by_name("target") #執行元素的移動操作ActionChains(driver).drag_and_drop(element, target).perform()
ActionChains 類不僅僅是只包含了上面的三個方法,下面將方法列出:
class ActionChains(driver)
driver:The WebDriver instance which performs user actions.
Generate user actions. All actions are stored in the ActionChains object. Call perform() to fire stored actions.
– perform()
Performs all stored actions.
– click(on_element=None)
Clicks an element.
on_element:The element to click. If None, clicks on current mouse position.
– click_and_hold(on_element)
Holds down the left mouse button on an element.
on_element:The element to mouse down. If None, clicks on current mouse position.
– context_click(on_element)
Performs a context-click (right click) on an element.
on_element:The element to context-click. If None, clicks on current mouse position.
– double_click(on_element)
Double-clicks an element.
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/