selenium知识点整理&汇总我爱编程

Selenium笔记(5)动作链

2018-05-10  本文已影响79人  王南北丶

本文集链接:https://www.jianshu.com/nb/25338984

简介

一般来说我们与页面的交互可以使用Webelement的方法来进行点击等操作。但是,有时候我们需要一些更复杂的动作,类似于拖动,双击,长按等等。

这时候就需要用到我们的Action Chains(动作链)了。


简例

from selenium.webdriver import ActionChains

element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

actions = ActionChains(driver)
actions.drag_and_drop(element, target)
actions.perform()

在导入动作链模块以后,需要声明一个动作链对象,在声明时将webdriver当作参数传入,并将对象赋值给一个actions变量。

然后我们通过这个actions变量,调用其内部附带的各种动作方法进行操作。

注:在调用各种动作方法后,这些方法并不会马上执行,而是会按你代码的顺序存储在ActionChains对象的队列中。当你调用perform()时,这些动作才会依次开始执行。


常用动作方法


完整文档

class selenium.webdriver.common.action_chains.``ActionChains(driver)

Bases: object

ActionChains are a way to automate low level interactions such as mouse movements, mouse button actions, key press, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop.

Generate user actions.

When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.

ActionChains can be used in a chain pattern:

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

Or actions can be queued up one by one, then performed.:

menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")

actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()

Either way, the actions are performed in the order they are called, one after another.

上一篇下一篇

猜你喜欢

热点阅读