生活随笔
收集整理的這篇文章主要介紹了
Python selenium操作浏览器全屏截图
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近完成一個需求,需要對監控頁面全屏截圖,并存儲成圖片上傳到oss。
先簡短記錄下最終的解決方式,后續有空完善細節及代碼注釋.
網上找了很多資料,全屏截圖的確可以,但是如果有代碼小scroll的頁面無法成功全屏截圖,解決方式是:
execute_script
= """(function () {var y = 0;var step = 100;window.scroll(0, 0);function f() {if (y < document.body.scrollHeight) {y += step;window.scroll(0, y);setTimeout(f, 50);} else {window.scroll(0, 0);document.title += "scroll-done";}}setTimeout(f, 1000);})();
"""
import time
from selenium
import webdriver
from selenium
.webdriver
.chrome
.options
import Options
def screen_shot(image_path
, shot_url
: str, slep_time
: int = 5):chrome_options
= Options
()chrome_options
.add_argument
('--no-sandbox')chrome_options
.add_argument
('--headless')chrome_options
.add_argument
('--disable-gpu')driver
= webdriver
.Chrome
(executable_path
="/Users/fan/Applications/chromedriver",options
=chrome_options
)try:driver
.get
(shot_url
)width
= max(1920, driver
.execute_script
("return document.documentElement.scrollWidth"))height
= driver
.execute_script
("return document.documentElement.scrollHeight")driver
.set_window_size
(width
+ 20, height
+ 20)driver
.execute_script
(execute_script
)for i
in range(30):if 'scroll-done' in driver
.title
:breaktime
.sleep
(slep_time
)driver
.get_screenshot_as_file
(image_path
)except Exception
as e
:if 'ERR_NAME_NOT_RESOLVED' in str(e
):raise Exception
(f'{shot_url}無法訪問,請檢查鏈接是否正確')raise Exception
(f'{shot_url}截圖失敗,{str(e)}')finally:if driver
:driver
.close
()driver
.quit
()return image_path
總結
以上是生活随笔為你收集整理的Python selenium操作浏览器全屏截图的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。