python中的selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離
更新時間:2022年02月11日 16:07:33 作者:呆萌的代Ma
這篇文章主要介紹了python中的selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離,下文有關selenium的資料介紹有一定的參考價值,需要的小伙伴可以參考一下
需要selenium控制的chrome向下滑動,自動加載一些內(nèi)容,核心代碼是:
browser.execute_script("window.scrollBy(0,300)")
這行可以向下滑動300個像素
需要的工具函數(shù)如下:
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: ?# 循環(huán)向下滑動 ? ? ? ? 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: ?# 循環(huán)向下滑動 ? ? ? ? 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()
到此這篇關于python中的selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離的文章就介紹到這了,更多相關selenium實現(xiàn)自動向下滾動頁面并指定最大滑動距離內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python 利用已有Ner模型進行數(shù)據(jù)清洗合并代碼
今天小編就為大家分享一篇python 利用已有Ner模型進行數(shù)據(jù)清洗合并代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12詳談在flask中使用jsonify和json.dumps的區(qū)別
下面小編就為大家分享一篇詳談在flask中使用jsonify和json.dumps的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03