【Python自动化】之利用JS操作页面滚动条(新)

如何操作页面中的滚动条,有以下几个方法:

 

一、查找可见元素进行滚动页面(通用)

方法一:

①移动到元素element对象的”顶端“,与当前窗口的”顶部“对齐(默认true)

scrollIntoView_js = "arguments[0].scrollIntoView();" 或 scrollIntoView_js = "arguments[0].scrollIntoView(true);"

    # 下滑到可见元素
    scrollIntoView_js = "arguments[0].scrollIntoView();"
# 确定按钮 sortSureBtn_loc = (By.CSS_SELECTOR, ".footer>button.el-button--primary")
# 查找可见元素进行下滑,滑动至最下面的按钮 self.executeScript(loc.scrollIntoView_js, loc.sortSureBtn_loc)

结果:

②移动到元素element对象的“底端”,与当前窗口的“底部”对齐

scrollIntoView_js = "arguments[0].scrollIntoView(false);"

    # 下滑到可见元素
    scrollIntoView_js = "arguments[0].scrollIntoView(false);"

    # 确定按钮
    sortSureBtn_loc = (By.CSS_SELECTOR, ".footer>button.el-button--primary")



    # 查找可见元素进行下滑,滑动至最下面的按钮
    self.executeScript(loc.scrollIntoView_js, loc.sortSureBtn_loc)

结果:

方法二:

location_once_scrolled_into_view,此方法把某个元素滚动到可视范围内

def webDriverWait(self, loc):
    """显式等待,查找单元素"""
    WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(loc))
    return self.find_element(loc)

def el_View(self, loc):
        """滑动到可见的元素"""
        self.webDriverWait(loc).location_once_scrolled_into_view

# 确定按钮
sortSureBtn_loc = (By.CSS_SELECTOR, ".footer>button.el-button--primary")

# 查找可见元素进行下滑,滑动至最下面的按钮
self.el_View(loc.sortSureBtn_loc)

二、下滑页面内嵌的滚动条(内嵌)

首先定位此滚轮在页面哪个标签下,class="boxcontainer"

    def executeScript(self, js, loc):
        """执行JS元素"""
        sleep(1)
        if loc == None:
            return self.driver.execute_script(js)
        else:
            return self.driver.execute_script(js, self.webDriverWait(loc))


# 下滑内嵌滚动条
scrollTop_js = "var q = document.getElementsByClassName('boxcontainer')[0].scrollTop=10000"


# 下滑内嵌滚动条
self.executeScript(loc.scrollTop_js, None)

三、 浏览器自带外边的滚动条滑动(外嵌)

①滚动条下拉距离

window.scrollBy(0,100)
# 或者 var q
=document.documentElement.scrollTop=10000

②滚动条上拉距离

window.scrollBy(0,-100):
# 或者 var q
=document.documentElement.scrollTop=0

 

③滚动条滑到底部

window.scrollTo(0,document.body.scrollHeight)

④滚动条滑到顶部

window.scrollTo(document.body.scrollHeight,0)

四、附录

①感谢幸运球与倒霉蛋的《selenium中元素操作之浏览器窗口滚动&网页日期控件操作(js操作)(五)

②感谢的《python+selenium 滚动条/内嵌滚动条循环下滑,判断是否滑到最底部

 

posted @ 2022-06-23 15:16  Owen_ET  阅读(872)  评论(0编辑  收藏  举报