当前环境:
Windows 10 + Python 3.7 + selenium==3.141.0 + urllib3==1.26.2 + Chromium 65.0.3312.0 (32 位)
用selenium做自动化,有时候会遇到需要模拟鼠标操作才能进行的情况,比如单击、双击、点击鼠标右键、拖拽等等。而selenium给我们提供了一个类来处理这类事件——ActionChains。
引入库:
from selenium.webdriver.common.action_chains import ActionChains
单击的例子:
# -*- coding: utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
if __name__ == '__main__':
import os
os.system('chcp 65001')
os.system('taskkill /F /IM chromedriver.exe')
# Chrome 路径
CHROME_PATH = r'C:\Program Files (x86)\65.0.3312.0\chrome-win32\chrome.exe'
# ChromeDriver 路径
CHROMEDRIVER_PATH = r'C:\Program Files (x86)\65.0.3312.0\chromedriver_win32\chromedriver.exe'
options = webdriver.ChromeOptions()
# 取消 Chrome 正受到自动测试软件的控制
options.add_experimental_option("excludeSwitches", ["enable-automation"])
# 取消 请停用以开发者模式运行的扩展程序
options.add_experimental_option("useAutomationExtension", False)
# 手动指定使用的浏览器位置
options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, options=options)
url = 'https://www.baidu.com'
driver.get(url)
print(driver.title)
# 百度一下
element = driver.find_element_by_id('su')
# 方式一
# aciton = ActionChains(driver)
# aciton.click(element).perform()
# 方式二
ActionChains(driver).move_to_element(element).click().perform()
# 退出浏览器
driver.quit()
''' ActionChains方法列表 click(on_element=None) # 单击鼠标左键 click_and_hold(on_element=None) # 点击鼠标左键,不松开 context_click(on_element=None) # 点击鼠标右键 double_click(on_element=None) # 双击鼠标左键 drag_and_drop(source, target) # 拖拽到某个元素然后松开 drag_and_drop_by_offset(source, xoffset, yoffset) # 拖拽到某个坐标然后松开 key_down(value, element=None) # 按下某个键盘上的键 key_up(value, element=None) # 松开某个键 move_by_offset(xoffset, yoffset) # 鼠标从当前位置移动到某个坐标 move_to_element(to_element) # 鼠标移动到某个元素 move_to_element_with_offset(to_element, xoffset, yoffset) # 移动到距某个元素(左上角坐标)多少距离的位置 perform() # 执行链中的所有动作 release(on_element=None) # 在某个元素位置松开鼠标左键 send_keys(*keys_to_send) # 发送某个键到当前焦点的元素 send_keys_to_element(element, *keys_to_send) # 发送某个键到指定元素 ''' ''' 实现代码: Python37-32\Lib\site-packages\selenium\webdriver\common\action_chains.py ''' ''' 参考: https://www.cnblogs.com/ziyewu/p/14440975.html https://blog.youkuaiyun.com/myh919/article/details/134217867 '''
本文介绍了如何在Windows10环境下使用Python3.7和Selenium3.141.0版本处理需要模拟鼠标操作的网页自动化任务,重点讲解了ActionChains类及其方法,如单击、双击、鼠标右键和拖拽等。
1199

被折叠的 条评论
为什么被折叠?



