参考文档:
- https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.touch_actions
- https://www.selenium.dev/selenium/docs/api/py/webdriver/selenium.webdriver.common.touch_actions.html
介绍
- 类似于ActionChains,AchtionChains只是针对PC端程序鼠标模拟的一系列操作,对H5页面操作是无效的。TouchAction可以对H5页面操作,通过TouchAction可以实现点击、滑动、拖拽、多点触控,以及模拟手势的各种操作
手势控制
- tap 在指定元素上敲击
- double_tap 在指定元素上双敲击
- tap_and_hold 在指定元素上点击但不释放
- move 手势移动指定偏移(未释放)
- release 释放手势
- scroll 手势点击并滚动
- scroll_from_element 从某个元素位置开始手势点击并滚动(向下滑动为负数,向上滑动为正数)
- long_press 长按元素
- flick 手势滑动
- flick_element 从某个元素位置开始手势滑动(向上滑动为负数,向下滑动为正数)
- perform 执行
例子
import time
from selenium import webdriver
from selenium.webdriver import TouchActions
from selenium.webdriver.common.by import By
class TestTouchAction:
def setup(self):
option = webdriver.ChromeOptions()
option.add_experimental_option('w3c', False)
self.driver = webdriver.Chrome(options=option)
self.driver.implicitly_wait(5)
self.driver.maximize_window()
def teardown(self):
self.driver.quit()
def test_scroll_button(self):
"""
打开百度
在搜索框中输入'selenium测试'
通过TouchAction点击搜索框
滑动到底部,点击下一页
关闭chrome
"""
self.driver.get('https://www.baidu.com/')
input_element = self.driver.find_element(By.ID, 'kw')
input_element.send_keys('selenium测试')
button_element = self.driver.find_element(By.ID, 'su')
button_element.click()
action = TouchActions(self.driver)
action.scroll_from_element(button_element, 0, 10000)
action.perform()
next_element = self.driver.find_element_by_css_selector('#page > div > a.n')
next_element.click()
time.sleep(3)