Selenium提供了一个类ActionChains来处理模拟鼠标事件,如单击、双击、拖动等。

基本语法:

  1. class ActionChains(object):
  2. """
  3. ActionChains are a way to automate low level interactions such as
  4. mouse movements, mouse button actions, key press, and context menu interactions.
  5. This is useful for doing more complex actions like hover over and drag and drop.
  6.  
  7. Generate user actions.
  8. When you call methods for actions on the ActionChains object,
  9. the actions are stored in a queue in the ActionChains object.
  10. When you call perform(), the events are fired in the order they
  11. are queued up.
  12.  
  13. ActionChains can be used in a chain pattern::
  14.  
  15. menu = driver.find_element_by_css_selector(".nav")
  16. hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
  17.  
  18. ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
  19.  
  20. Or actions can be queued up one by one, then performed.::
  21.  
  22. menu = driver.find_element_by_css_selector(".nav")
  23. hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
  24.  
  25. actions = ActionChains(driver)
  26. actions.move_to_element(menu)
  27. actions.click(hidden_submenu)
  28. actions.perform()
  29.  
  30. Either way, the actions are performed in the order they are called, one after
  31. another.
  32. """
  33.  
  34. def __init__(self, driver):
  35. """
  36. Creates a new ActionChains.
  37.  
  38. :Args:
  39. - driver: The WebDriver instance which performs user actions.
  40. """
  41. self._driver = driver
  42. self._actions = []
  43. if self._driver.w3c:
  44. self.w3c_actions = ActionBuilder(driver)
  45.  
  46. def perform(self):
  47. """
  48. Performs all stored actions.
  49. """
  50. if self._driver.w3c:
  51. self.w3c_actions.perform()
  52. else:
  53. for action in self._actions:
  54. action()
  55.  
  56. def reset_actions(self):
  57. """
  58. Clears actions that are already stored on the remote end.
  59. """
  60. if self._driver.w3c:
  61. self._driver.execute(Command.W3C_CLEAR_ACTIONS)
  62. else:
  63. self._actions = []
  64.  
  65. def click(self, on_element=None):
  66. """
  67. Clicks an element.
  68.  
  69. :Args:
  70. - on_element: The element to click.
  71. If None, clicks on current mouse position.
  72. """
  73. if self._driver.w3c:
  74. self.w3c_actions.pointer_action.click(on_element)
  75. self.w3c_actions.key_action.pause()
  76. self.w3c_actions.key_action.pause()
  77. else:
  78. if on_element:
  79. self.move_to_element(on_element)
  80. self._actions.append(lambda: self._driver.execute(
  81. Command.CLICK, {'button': 0}))
  82. return self
  83.  
  84. def click_and_hold(self, on_element=None):
  85. """
  86. Holds down the left mouse button on an element.
  87.  
  88. :Args:
  89. - on_element: The element to mouse down.
  90. If None, clicks on current mouse position.
  91. """
  92. if self._driver.w3c:
  93. self.w3c_actions.pointer_action.click_and_hold(on_element)
  94. self.w3c_actions.key_action.pause()
  95. if on_element:
  96. self.w3c_actions.key_action.pause()
  97. else:
  98. if on_element:
  99. self.move_to_element(on_element)
  100. self._actions.append(lambda: self._driver.execute(
  101. Command.MOUSE_DOWN, {}))
  102. return self
  103.  
  104. def context_click(self, on_element=None):
  105. """
  106. Performs a context-click (right click) on an element.
  107.  
  108. :Args:
  109. - on_element: The element to context-click.
  110. If None, clicks on current mouse position.
  111. """
  112. if self._driver.w3c:
  113. self.w3c_actions.pointer_action.context_click(on_element)
  114. self.w3c_actions.key_action.pause()
  115. else:
  116. if on_element:
  117. self.move_to_element(on_element)
  118. self._actions.append(lambda: self._driver.execute(
  119. Command.CLICK, {'button': 2}))
  120. return self
  121.  
  122. def double_click(self, on_element=None):
  123. """
  124. Double-clicks an element.
  125.  
  126. :Args:
  127. - on_element: The element to double-click.
  128. If None, clicks on current mouse position.
  129. """
  130. if self._driver.w3c:
  131. self.w3c_actions.pointer_action.double_click(on_element)
  132. for _ in range(4):
  133. self.w3c_actions.key_action.pause()
  134. else:
  135. if on_element:
  136. self.move_to_element(on_element)
  137. self._actions.append(lambda: self._driver.execute(
  138. Command.DOUBLE_CLICK, {}))
  139. return self
  140.  
  141. def drag_and_drop(self, source, target):
  142. """
  143. Holds down the left mouse button on the source element,
  144. then moves to the target element and releases the mouse button.
  145.  
  146. :Args:
  147. - source: The element to mouse down.
  148. - target: The element to mouse up.
  149. """
  150. if self._driver.w3c:
  151. self.w3c_actions.pointer_action.click_and_hold(source) \
  152. .move_to(target) \
  153. .release()
  154. for _ in range(3):
  155. self.w3c_actions.key_action.pause()
  156. else:
  157. self.click_and_hold(source)
  158. self.release(target)
  159. return self
  160.  
  161. def drag_and_drop_by_offset(self, source, xoffset, yoffset):
  162. """
  163. Holds down the left mouse button on the source element,
  164. then moves to the target offset and releases the mouse button.
  165.  
  166. :Args:
  167. - source: The element to mouse down.
  168. - xoffset: X offset to move to.
  169. - yoffset: Y offset to move to.
  170. """
  171. if self._driver.w3c:
  172. self.w3c_actions.pointer_action.click_and_hold(source) \
  173. .move_to_location(xoffset, yoffset) \
  174. .release()
  175. for _ in range(3):
  176. self.w3c_actions.key_action.pause()
  177. else:
  178. self.click_and_hold(source)
  179. self.move_by_offset(xoffset, yoffset)
  180. self.release()
  181. return self
  182.  
  183. def key_down(self, value, element=None):
  184. """
  185. Sends a key press only, without releasing it.
  186. Should only be used with modifier keys (Control, Alt and Shift).
  187.  
  188. :Args:
  189. - value: The modifier key to send. Values are defined in `Keys` class.
  190. - element: The element to send keys.
  191. If None, sends a key to current focused element.
  192.  
  193. Example, pressing ctrl+c::
  194.  
  195. ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
  196.  
  197. """
  198. if element:
  199. self.click(element)
  200. if self._driver.w3c:
  201. self.w3c_actions.key_action.key_down(value)
  202. self.w3c_actions.pointer_action.pause()
  203. else:
  204. self._actions.append(lambda: self._driver.execute(
  205. Command.SEND_KEYS_TO_ACTIVE_ELEMENT,
  206. {"value": keys_to_typing(value)}))
  207. return self
  208.  
  209. def key_up(self, value, element=None):
  210. """
  211. Releases a modifier key.
  212.  
  213. :Args:
  214. - value: The modifier key to send. Values are defined in Keys class.
  215. - element: The element to send keys.
  216. If None, sends a key to current focused element.
  217.  
  218. Example, pressing ctrl+c::
  219.  
  220. ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()
  221.  
  222. """
  223. if element:
  224. self.click(element)
  225. if self._driver.w3c:
  226. self.w3c_actions.key_action.key_up(value)
  227. self.w3c_actions.pointer_action.pause()
  228. else:
  229. self._actions.append(lambda: self._driver.execute(
  230. Command.SEND_KEYS_TO_ACTIVE_ELEMENT,
  231. {"value": keys_to_typing(value)}))
  232. return self
  233.  
  234. def move_by_offset(self, xoffset, yoffset):
  235. """
  236. Moving the mouse to an offset from current mouse position.
  237.  
  238. :Args:
  239. - xoffset: X offset to move to, as a positive or negative integer.
  240. - yoffset: Y offset to move to, as a positive or negative integer.
  241. """
  242. self._actions.append(lambda: self._driver.execute(
  243. Command.MOVE_TO, {
  244. 'xoffset': int(xoffset),
  245. 'yoffset': int(yoffset)}))
  246. return self
  247.  
  248. def move_to_element(self, to_element):
  249. """
  250. Moving the mouse to the middle of an element.
  251.  
  252. :Args:
  253. - to_element: The WebElement to move to.
  254. """
  255. if self._driver.w3c:
  256. self.w3c_actions.pointer_action.move_to(to_element)
  257. self.w3c_actions.key_action.pause()
  258. else:
  259. self._actions.append(lambda: self._driver.execute(
  260. Command.MOVE_TO, {'element': to_element.id}))
  261. return self
  262.  
  263. def move_to_element_with_offset(self, to_element, xoffset, yoffset):
  264. """
  265. Move the mouse by an offset of the specified element.
  266. Offsets are relative to the top-left corner of the element.
  267.  
  268. :Args:
  269. - to_element: The WebElement to move to.
  270. - xoffset: X offset to move to.
  271. - yoffset: Y offset to move to.
  272. """
  273. if self._driver.w3c:
  274. self.w3c_actions.pointer_action.move_to(to_element, xoffset, yoffset)
  275. self.w3c_actions.key_action.pause()
  276. else:
  277. self._actions.append(
  278. lambda: self._driver.execute(Command.MOVE_TO, {
  279. 'element': to_element.id,
  280. 'xoffset': int(xoffset),
  281. 'yoffset': int(yoffset)}))
  282. return self
  283.  
  284. def release(self, on_element=None):
  285. """
  286. Releasing a held mouse button on an element.
  287.  
  288. :Args:
  289. - on_element: The element to mouse up.
  290. If None, releases on current mouse position.
  291. """
  292. if self._driver.w3c:
  293. self.w3c_actions.pointer_action.release()
  294. self.w3c_actions.key_action.pause()
  295. else:
  296. if on_element:
  297. self.move_to_element(on_element)
  298. self._actions.append(lambda: self._driver.execute(Command.MOUSE_UP, {}))
  299. return self
  300.  
  301. def send_keys(self, *keys_to_send):
  302. """
  303. Sends keys to current focused element.
  304.  
  305. :Args:
  306. - keys_to_send: The keys to send. Modifier keys constants can be found in the
  307. 'Keys' class.
  308. """
  309. if self._driver.w3c:
  310. self.w3c_actions.key_action.send_keys(keys_to_send)
  311. else:
  312. self._actions.append(lambda: self._driver.execute(
  313. Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {'value': keys_to_typing(keys_to_send)}))
  314. return self
  315.  
  316. def send_keys_to_element(self, element, *keys_to_send):
  317. """
  318. Sends keys to an element.
  319.  
  320. :Args:
  321. - element: The element to send keys.
  322. - keys_to_send: The keys to send. Modifier keys constants can be found in the
  323. 'Keys' class.
  324. """
  325. if self._driver.w3c:
  326. self.w3c_actions.key_action.send_keys(keys_to_send, element=element)
  327. else:
  328. self._actions.append(lambda: element.send_keys(*keys_to_send))
  329. return self
  330.  
  331. # Context manager so ActionChains can be used in a 'with .. as' statements.
  332. def __enter__(self):
  333. return self # Return created instance of self.
  334.  
  335. def __exit__(self, _type, _value, _traceback):
  336. pass # Do nothing, does not require additional cleanup.

  方法列表

  1. perform(self): ---执行链中的所有动作
  2. reset_actions(self): ---清除存储在远端的动作
  3. click(self, on_element=None): ---鼠标左键单击
  4. click_and_hold(self, on_element=None): --鼠标左键单击,不松开
  5. context_click(self, on_element=None): ---鼠标右键单击
  6. double_click(self, on_element=None): ---鼠标左键双击
  7. drag_and_drop(self, source, target): ---拖拽到某个元素后松开
  8. drag_and_drop_by_offset(self, source, xoffset, yoffset): ---拖拽到某个坐标后松开
  9. key_down(self, value, element=None): ---某个键盘键被按下
  10. key_up(self, value, element=None): ---松开某个键
  11. move_by_offset(self, xoffset, yoffset): ---鼠标移动到某个坐标
  12. move_to_element(self, to_element): ---鼠标移动到某个元素
  13. move_to_element_with_offset(self, to_element, xoffset, yoffset): ---移动到距某个元素(左上角)多少的位置
  14. release(self, on_element=None): ---在某元素上松开鼠标
  15. send_keys(self, *keys_to_send): ---发送某些值到当前焦点元素
  16. send_keys_to_element(self, element, *keys_to_send): ---发送某些值到指定元素

基本用法

  1. 链式写法
  2. ActionChains(driver).click(clk_btn).context_click(right_btn).perform()
  3.  
  4. 分步写法
  5. # 补全化action
  6. actions = ActionChains(driver)
  7. # 装载单击动作
  8. actions.click()
  9. # 装载右击动作
  10. actions.context_click()
  11. # 执行所有被装载的动作
  12. actions.perform()

应用举例

  1. #!/usr/bin/env python
  2. # _*_ coding:utf-8 _*_
  3.  
  4. from selenium.webdriver.common.action_chains import ActionChains
  5. from selenium import webdriver
  6. import time
  7.  
  8. driver = webdriver.Chrome()
  9. driver.get("https://www.baidu.com/")
  10. driver.implicitly_wait(10)
  11.  
  12. # 右击百度新闻
  13. right_click = driver.find_element_by_xpath('//a[@name="tj_trnews"]')
  14. ActionChains(driver).context_click(right_click).perform()

参考 文档:

http://www.jb51.net/article/92682.htm

下拉滚动条

  方法一:

使用js脚本直接操作

  1. js="var q=document.documentElement.scrollTop=10000"
  1. driver.execute_script(js)

  方法二、

将滚动条手动到指定的位置,这种方法更常用

  1. target = driver.find_element_by_id("id_keypair")
  2. driver.execute_script("arguments[0].scrollIntoView();", target) #拖动到可见的元素去

  方法三、

发送TAB键

  1. from selenium.webdriver.common.keys import Keys
  2. driver.find_element_by_id("id_login_method_0").send_keys(Keys.TAB)

  方法四、

前段时间使用robotframe work框架时,selenium2library里面有一个非常好用的功能Focus,会自动定位到元素,研读一下源码:

  1. def focus(self, locator):
  2. """Sets focus to element identified by `locator`."""
  3. element = self._element_find(locator, True, True)
  4. self._current_browser().execute_script("arguments[0].focus();", element)

  从源码中我们可以看到,此方法与我们在python自己写的方法二)一致,工具给我们做了封装。

selenium模拟鼠标操作的更多相关文章

  1. python+selenium模拟鼠标操作

    from selenium.webdriver.common.action_chains import ActionChains #导入鼠标相关的包 ------------------------- ...

  2. 模拟鼠标操作(ActionChains)(转 侵删)

    在日常的测试中,经常会遇到需要鼠标去操作的一些事情,比如说悬浮菜单.拖动验证码等,这一节我们来学习如何使用webdriver模拟鼠标的操作 首页模拟鼠标的操作要首先引入ActionChains的包 f ...

  3. Python+Selenium自动化 模拟鼠标操作

    Python+Selenium自动化 模拟鼠标操作   在webdriver中,鼠标的一些操作如:双击.右击.悬停.拖动等都被封装在ActionChains类中,我们只用在需要使用的时候,导入这个类就 ...

  4. Java&Selenium 模拟鼠标方法封装

    Java&Selenium 模拟鼠标方法封装 package util; import org.openqa.selenium.By; import org.openqa.selenium.W ...

  5. selenium + python(鼠标操作)

    关于最近学习selenium自动化测试鼠标操作的一些总结 常见的鼠标操作

  6. windows7如何用键盘模拟鼠标操作

    windows7如何用键盘模拟鼠标操作 https://jingyan.baidu.com/article/6dad5075104907a123e36e38.html 听语音 37453人看了这个视频 ...

  7. webdriver模拟鼠标操作

    ActionChains 生成模拟用户操作的对象 from selenium.webdriver.common.action_chains import ActionChains ActionChai ...

  8. python selenium模拟滑动操作

    selenium.webdriver提供了所有WebDriver的实现,目前支持FireFox.phantomjs.Chrome.Ie和Remote quit()方法会退出浏览器,而close()方法 ...

  9. Selenium键盘鼠标操作总结

    鼠标操作 org.openqa.selenium.interactions.Actions 1.给元素设置焦点. 有时对于a标签等,为了不跳转到别的链接,但是需要设置焦点时就可使用. action.m ...

随机推荐

  1. docker - 修改镜像/容器文件或者 "Docker root dir" 的在宿主机上的存储位置

    背景 之前在使用docker的时候,由于启动container的时候用的是默认的mount(路径为 /var/lib/docker),这个目录对应的硬盘空间有限,只有200G左右.现在随着程序运行,有 ...

  2. Android 开发工具类 31_WebService 获取手机号码归属地

    AndroidInteractWithWebService.xml <?xml version="1.0" encoding="utf-8"?> & ...

  3. 一步步用svg做一个声波扩散动画

    有个项目需要在某个坐标显示一个声波扩散(不知道这个表达对不对)的动画. 这种需求一般做法有几种,一种做成gif图片,然后贴上去,一种是用html+css3完成,要么就是画上去,这画又分两种,一种是Ca ...

  4. GRU

    GRU模型(比LSTM减少了计算量) LSTM的模型,LSTM的重复网络模块的结构很复杂,它实现了三个门计算,即遗忘门.输入门和输出门. 而GRU模型如下,它只有两个门了,分别为更新门和重置门,即图中 ...

  5. centos7-安装mysql5.6.36

    本地安装了mysql5.7, 但和springboot整合jpa时会出现 hibernateException, 不知道为什么, 换个mysql5.6版本的mysql,  源码安装, cmake一直过 ...

  6. equal&==&hashcode

    == 和 equals 的区别 Object类中的equals方法和“==”是一样的,没有区别,而String类,Integer类等等一些类,是重写了equals方法,才使得equals和“==不同” ...

  7. apache的rewrite规则来实现URL末尾是否带斜杠

    1.url: http://www.test.com/user/ 跟:http://www.test.com/user 这两个URL对于用户来说应该是一样的,但从编程的角度来说,它们可以不相同 但我们 ...

  8. Git的gitattributes文件详解

    转自:Git的gitattributes文件详解 Git的gitattributes文件是一个文本文件,文件中的一行定义一个路径的若干个属性. 1. gitattributes文件以行为单位设置一个路 ...

  9. 【设计模式】工厂模式 Factory Pattern

    1)简单工厂(不是模式) 简单工厂只是一种变成习惯,并非23种设计模式之一. 简单工厂提供将实例话那种类型留给运行时判断,而非编译时指定.简单工厂模式就是由一个工厂类根据传入的参数决定创建出哪一个类的 ...

  10. IOS第三方之SVProgressHUD

    这个第三方和MBProgressHUD差不多,也挺简单的. // // ViewController.m // ProgressHUD // // Created by City--Online on ...