python selenium 左右滑动操作 | 您所在的位置:网站首页 › 往左划屏幕 › python selenium 左右滑动操作 |
在自动化测试中,左右滑动页面有以下几种方式: 1. 使用`ActionChains`类: from selenium.webdriver import ActionChains slider_element = driver.find_element_by_xpath("//div[@class='slider']") action = ActionChains(driver) action.click_and_hold(slider_element).move_by_offset(200, 0).release().perform()使用`ActionChains`类可以模拟用户的操作。 首先,使用`find_element_by_xpath()`等方法找到要滑动的元素,例如一个带有滑块的容器。 然后,创建`ActionChains`对象,并使用`click_and_hold()`方法点击并按住滑块元素, 接着使用`move_by_offset()`方法指定滑动的偏移量(正数表示向右滑动,负数表示向左滑动), 然后释放滑块元素, 最后通过`perform()`方法执行滑动操作。 例: from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver import ActionChains 驱动 = webdriver.Chrome() 驱动.get("https://www.helloweba.net/demo/2017/unlock/") 驱动.maximize_window() # 查找滑动模块 unlock_element = 驱动.find_element(By.CSS_SELECTOR,".slide-to-unlock-handle") # 获取鼠标操作 mouse_oper = ActionChains(驱动) #对滑块按下鼠标左键并执行 mouse_oper.click_and_hold(unlock_element).perform() #拖动x轴移动x坐标 mouse_oper.move_by_offset(300,0).perform() #重置滑动框 mouse_oper.reset_actions() sleep(5) #退出 驱动.quit()2. 使用JavaScript滚动: slider_element = driver.find_element_by_xpath("//div[@class='slider']") driver.execute_script("arguments[0].scrollLeft += 200", slider_element)使用`execute_script()`方法执行JavaScript代码来实现滑动。 首先,使用`find_element_by_xpath()`等方法找到要滑动的元素, 例如一个带有滑块的容器。然后,使用JavaScript代码将滑块元素的`scrollLeft`属性增加指定的值(正数表示向右滑动,负数表示向左滑动),从而实现页面的滑动。 3. 使用Touch Actions类(移动设备测试): from selenium.webdriver import TouchActions slider_element = driver.find_element_by_xpath("//div[@class='slider']") action = TouchActions(driver) action.scroll(slider_element, 200, 0).perform()如果进行移动设备的测试,可以使用`TouchActions`类来模拟滑动操作。 首先,使用`find_element_by_xpath()`等方法找到要滑动的元素,例如一个带有滑块的容器。 然后,创建`TouchActions`对象,并使用`scroll()`方法指定滑动的偏移量(正数表示向右滑动,负数表示向左滑动), 最后通过`perform()`方法执行滑动操作。 |
CopyRight 2018-2019 实验室设备网 版权所有 |