UI 自动化中经常会用到屏幕滑动,selenium 提供的接口很少。记录一下常用的 js 语句以免忘记

window.scroll(x,y)
window.scrollBy(x,y)
window.scroll(0, document.documentElement.scrollHeight)
window.scroll(0, 0)
element.location_once_scrolled_into_view
或者
driver.execute_script('arguments[0].scrollIntoView({block: "start"})', element)
或者
driver.execute_script('arguments[0].scrollIntoView(true)', element)
driver.execute_script('arguments[0].scrollIntoView({block: "center"})', element)
driver.execute_script('arguments[0].scrollIntoView({block: "end"})', element)
或者
driver.execute_script('arguments[0].scrollIntoView(flase)', element)
js = "document.body.style.zoom='60%'"

封装一下便于调用

import time

from selenium import webdriver
import os

from selenium.webdriver.chrome.options import Options
class Scroll(object):
    """
    browser = driver
    """
    browser: object = None

    @property
    def driver(self):
        return self.__class__.browser

    @driver.setter
    def driver(self, driver):
        self.__class__.browser = driver

    @classmethod
    def scroll(cls, x, y):
        """
        移动x,y距离(以 0,0)为坐标
        :param x:
        :param y:
        :return:
        """
        script = f"window.scroll({x},{y})"
        cls.browser.execute_script(script)

    @classmethod
    def scroll_to_bottom(cls):
        """
        移动到底部
        :return:
        """
        full_screen_height = "document.documentElement.scrollHeight"
        script = f"window.scroll(0, {full_screen_height})"
        cls.browser.execute_script(script)

    @classmethod
    def scroll_to_top(cls):
        """
        回到顶部
        :return:
        """
        script = "window.scroll(0, 0)"
        cls.browser.execute_script(script)

    @staticmethod
    def scroll_to_element_top(element):
        """
        滑动至顶部对齐
        :param element:
        :return:
        """
        var = element.location_once_scrolled_into_view

    @classmethod
    def scroll_to_element_center(cls, element):
        """
        滑动至中间对齐
        :param element:
        :return:
        """
        cls.browser.execute_script('arguments[0].scrollIntoView({block: "center"})', element)

    @classmethod
    def scroll_to_element_bottom(cls, element):
        """
        滑动至底部对齐
        :return:
        """
        cls.browser.execute_script('arguments[0].scrollIntoView(false)', element)



chromedriver = os.getenv("CHROME_DRIVER")
options = Options()
options.add_argument("--start-maximized")

driver = webdriver.Chrome(executable_path=chromedriver, options=options)
driver.get("file:///C:/demo.html")

element = driver.find_element_by_id("demo")
Scroll.browser = driver

Scroll.scroll_until_element_displayed(element)
time.sleep(3)
Scroll.scroll_to_element_top(element)
time.sleep(3)
Scroll.scroll_to_element_center(element)
time.sleep(3)
Scroll.scroll_to_element_bottom(element)
time.sleep(3)
driver.quit()


↙↙↙阅读原文可查看相关链接,并与作者交流