[selenium] 浏览器滚动条滚动到指定位置

浏览器滚动条滚动到指定位置

利用driver.execute_script()来实现浏览器滚动条滚动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>scroll</title>
  <style type="text/css">
    .box {
      height: 10000px;
      width: 200px;
      background-color: red;
    }
  </style>
</head>
<body>
<div class="box">

</div>
</body>
</html>

保存为scroll.html

#!/usr/bin/env python
# coding: utf8
import os.path
import time

from selenium import webdriver

file_path = "file:///" + os.path.abspath("scroll.html")
driver = webdriver.Chrome()
driver.get(file_path)


time.sleep(2)
js = "document.documentElement.scrollTop = 10000"
driver.execute_script(js)

time.sleep(2)
js = "document.documentElement.scrollTop = 0"

time.sleep(2)
driver.quit()