Web自动化----模拟动作(鼠标,快捷键,拖拽)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains  # 导入包
import time

driver = webdriver.Chrome(executable_path='../../drivers/chrome89/chromedriver')
# driver.maximize_window()


# 1.模拟鼠标滑动操作
# 打开百度,鼠标滑动到更多上面,打开音乐页面

driver.get('https://www.baidu.com/')

more_btn = driver.find_element_by_xpath('//*[@name="tj_briicon"]')  # 找到‘更多’元素
action = ActionChains(driver)     # 构建动作
action.move_to_element(more_btn)  # 移动到‘更多’元素上

mp3 = driver.find_element_by_xpath('//*[@name="tj_mp3"]')  # 找到‘音乐’元素
action.move_to_element(mp3).click()                        # 移动到‘音乐’元素上,并点击

action.perform()  # 执行,构建完成之后一定要调用此方法


# 2.模拟快捷键操作
# 打开百度,输入helloword,然后快捷键全选,剪切,复制复制复制
driver.get('https://www.baidu.com/')

input_hello = driver.find_element_by_xpath('//input[@name="wd"]')  # 找到‘输入框’元素
input_hello.send_keys('helloword')                                 # 输入内容

actions_2 = ActionChains(driver)
actions_2.click(input_hello)

actions_2.key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL)   # Ctrl+a
actions_2.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL)   # Ctrl+c

actions_2.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL)   # Ctrl+v
actions_2.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL)   # Ctrl+v
actions_2.key_down(Keys.CONTROL).send_keys('v').key_up(Keys.CONTROL)   # Ctrl+v

actions_2.perform()  # 执行


# 3.模拟拖拽操作
# 打开百度地图,随机找一个点设置为起点,然后拖拽,随机的找一个点作为终点
driver.get('https://map.baidu.com/')

bd_map = driver.find_element_by_id('mask')                # 找到地图元素

actions_3 = ActionChains(driver)

actions_3.move_to_element(bd_map).context_click()         # 在地图中心的,模拟鼠标点击右键
actions_3.pause(3)                                        # 暂停3s (运行的太快了,会看不到效果)
start = driver.find_element_by_id('cmitem_start')         # 找到‘以此为起点’元素
actions_3.move_to_element(start).click()                  # 鼠标滑动到start 元素上,点击
actions_3.pause(3)

# 模拟鼠标右键点击地图,然后拖拽
actions_3.click_and_hold(bd_map).move_by_offset(xoffset=50, yoffset=10).release()
actions_3.pause(3)

actions_3.context_click()  # 模拟鼠标,点击右键
actions_3.pause(3)
end = driver.find_element_by_id('cmitem_end')
actions_3.move_to_element(end).click()
actions_3.pause(3)

actions_3.perform()  # 执行

 

posted @ 2021-05-20 10:53  Z_sun  阅读(535)  评论(0编辑  收藏  举报