日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python中的selenium實現自動向下滾動頁面并指定最大滑動距離_python

作者:呆萌的代Ma ? 更新時間: 2022-04-18 編程語言

需要selenium控制的chrome向下滑動,自動加載一些內容,核心代碼是:

browser.execute_script("window.scrollBy(0,300)")

這行可以向下滑動300個像素

需要的工具函數如下:

def roll_window_to_bottom(browser, stop_length=None, step_length=500):
? ? """selenium 滾動當前頁面,向下滑
? ? :param browser: selenium的webdriver
? ? :param stop_length: 滑動的最大值
? ? :param step_length: 每次滑動的值
? ? """
? ? original_top = 0
? ? while True: ?# 循環向下滑動
? ? ? ? if stop_length:
? ? ? ? ? ? if stop_length - step_length < 0:
? ? ? ? ? ? ? ? browser.execute_script("window.scrollBy(0,{})".format(stop_length))
? ? ? ? ? ? ? ? break
? ? ? ? ? ? stop_length -= step_length
? ? ? ? browser.execute_script("window.scrollBy(0,{})".format(step_length))
? ? ? ? time.sleep(0.5 + random.random()) ?# 停頓一下
? ? ? ? check_height = browser.execute_script(
? ? ? ? ? ? "return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;")
? ? ? ? if check_height == original_top: ?# 判斷滑動后距頂部的距離與滑動前距頂部的距離
? ? ? ? ? ? break
? ? ? ? original_top = check_height

使用示例:

from selenium import webdriver
import time
import random


def roll_window_to_bottom(browser, stop_length=None, step_length=500):
? ? """selenium 滾動當前頁面,向下滑
? ? :param browser: selenium的webdriver
? ? :param stop_length: 滑動的最大值
? ? :param step_length: 每次滑動的值
? ? """
? ? original_top = 0
? ? while True: ?# 循環向下滑動
? ? ? ? if stop_length:
? ? ? ? ? ? if stop_length - step_length < 0:
? ? ? ? ? ? ? ? browser.execute_script("window.scrollBy(0,{})".format(stop_length))
? ? ? ? ? ? ? ? break
? ? ? ? ? ? stop_length -= step_length

? ? ? ? browser.execute_script("window.scrollBy(0,{})".format(step_length))
? ? ? ? time.sleep(0.5 + random.random()) ?# 停頓一下
? ? ? ? check_height = browser.execute_script(
? ? ? ? ? ? "return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;")
? ? ? ? if check_height == original_top: ?# 判斷滑動后距頂部的距離與滑動前距頂部的距離
? ? ? ? ? ? break
? ? ? ? original_top = check_height


def main():
? ? option = webdriver.ChromeOptions()
? ? option.add_argument('lang=zh_CN.UTF-8') ?# 設置
? ? browser = webdriver.Chrome(chrome_options=option, desired_capabilities={"page_load_strategy": "none"})
? ? browser.get("http://news.baidu.com/")
? ? roll_window_to_bottom(browser, stop_length=700)


if __name__ == '__main__':
? ? main()

原文鏈接:https://blog.csdn.net/weixin_35757704/article/details/122763602

欄目分類
最近更新