Python實(shí)現(xiàn)網(wǎng)頁(yè)截圖(PyQT5)過(guò)程解析
方案說(shuō)明
功能要求:實(shí)現(xiàn)網(wǎng)頁(yè)加載后將頁(yè)面截取成長(zhǎng)圖片
涉及模塊:PyQT5 PIL
邏輯說(shuō)明:
1:完成窗口設(shè)置,利用PyQT5 QWebEngineView加載網(wǎng)頁(yè)地址,待網(wǎng)頁(yè)加載完成后,調(diào)用check_pag;
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle('易哈佛') self.temp_height = 0 self.setWindowFlag(Qt.WindowMinMaxButtonsHint, False) # 禁用最大化,最小化 # self.setWindowFlag(Qt.WindowStaysOnTopHint, True) # 窗口頂置 self.setWindowFlag(Qt.FramelessWindowHint, True) # 窗口無(wú)邊框 def urlScreenShot(self, url): self.browser = QWebEngineView() self.browser.load(QUrl(url)) geometry = self.chose_screen() self.setGeometry(geometry) self.browser.loadFinished.connect(self.check_page) self.setCentralWidget(self.browser) def get_page_size(self): size = self.browser.page().contentsSize() self.set_height = size.height() self.set_width = size.width() return size.width(), size.height() def chose_screen(self): width, height = 750, 1370 desktop = QApplication.desktop() screen_count = desktop.screenCount() for i in range(0, screen_count): rect = desktop.availableGeometry(i) s_width, s_height = rect.width(), rect.height() if s_width > width and s_height > height: return QRect(rect.left(), rect.top(), width, height) return QRect(0, 0, width, height) if __name__ == '__main__': app = QApplication(sys.argv) win = MainWindow() win.show() app.exit(app.exec_())
2:收集頁(yè)面高度,并計(jì)算分次截屏的次數(shù)和余量高度;實(shí)例化圖片合并工具,設(shè)置定時(shí)器,超時(shí)信號(hào)發(fā)出后,執(zhí)行exe_command;
def check_page(self): p_width, p_height = self.get_page_size() self.page, self.over_flow_size = divmod(p_height, self.height()) if self.page == 0: self.page = 1 self.ssm = ScreenShotMerge(self.page, self.over_flow_size) self.timer = QTimer(self) self.timer.timeout.connect(self.exe_command) self.timer.setInterval(400) self.timer.start()
3:exe_command用來(lái)控制截圖次數(shù),并在每次截圖完成后控制網(wǎng)頁(yè)向下滑屏幕的高度;所有的頁(yè)面都已截取時(shí),完成圖片合并。
def exe_command(self): if self.page > 0: self.screen_shot() self.run_js() elif self.page < 0: self.timer.stop() self.ssm.image_merge() self.close() elif self.over_flow_size > 0: self.screen_shot() self.page -= 1 def run_js(self): script = """ var scroll = function (dHeight) { var t = document.documentElement.scrollTop var h = document.documentElement.scrollHeight dHeight = dHeight || 0 var current = t + dHeight if (current > h) { window.scrollTo(0, document.documentElement.clientHeight) } else { window.scrollTo(0, current) } } """ command = script + '\n scroll({})'.format(self.height()) self.browser.page().runJavaScript(command)
4:screen_shot在每次截圖完成后將圖片保存,并將圖片對(duì)象由圖片合并根據(jù)保存到列表中。
def screen_shot(self): screen = QApplication.primaryScreen() winid = self.browser.winId() pix = screen.grabWindow(int(winid)) name = '{}/temp.png'.format(self.ssm.root_path) pix.save(name) self.ssm.add_im(name)
5:截圖合并工具,在每次截圖完成后將圖片對(duì)象保存,完成余量截圖的重繪和截圖的合并。
class ScreenShotMerge(): def __init__(self, page, over_flow_size): self.im_list = [] self.page = page self.over_flow_size = over_flow_size self.get_path() def get_path(self): self.root_path = Path(__file__).parent.joinpath('temp') if not self.root_path.exists(): self.root_path.mkdir(parents=True) self.save_path = self.root_path.joinpath('merge.png') def add_im(self, path): if len(self.im_list) == self.page: im = self.reedit_image(path) else: im = Image.open(path) im.save('{}/{}.png'.format(self.root_path, len(self.im_list) + 1)) self.im_list.append(im) def get_new_size(self): max_width = 0 total_height = 0 # 計(jì)算合成后圖片的寬度(以最寬的為準(zhǔn))和高度 for img in self.im_list: width, height = img.size if width > max_width: max_width = width total_height += height return max_width, total_height def image_merge(self, ): if len(self.im_list) > 1: max_width, total_height = self.get_new_size() # 產(chǎn)生一張空白圖 new_img = Image.new('RGB', (max_width - 15, total_height), 255) x = y = 0 for img in self.im_list: width, height = img.size new_img.paste(img, (x, y)) y += height new_img.save(self.save_path) print('截圖成功:', self.save_path) else: obj = self.im_list[0] width, height = obj.size left, top, right, bottom = 0, 0, width, height box = (left, top, right, bottom) region = obj.crop(box) new_img = Image.new('RGB', (width, height), 255) new_img.paste(region, box) new_img.save(self.save_path) print('截圖成功:', self.save_path) def reedit_image(self, path): obj = Image.open(path) width, height = obj.size left, top, right, bottom = 0, height - self.over_flow_size, width, height box = (left, top, right, bottom) region = obj.crop(box) return region
截圖功能完整代碼
#!/usr/bin/env python # -*- coding:UTF-8 -*- # Author:Leslie-x import sys from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtWebEngineWidgets import * from PIL import Image from pathlib import Path class ScreenShotMerge(): def __init__(self, page, over_flow_size): self.im_list = [] self.page = page self.over_flow_size = over_flow_size self.get_path() def get_path(self): self.root_path = Path(__file__).parent.joinpath('temp') if not self.root_path.exists(): self.root_path.mkdir(parents=True) self.save_path = self.root_path.joinpath('merge.png') def add_im(self, path): if len(self.im_list) == self.page: im = self.reedit_image(path) else: im = Image.open(path) im.save('{}/{}.png'.format(self.root_path, len(self.im_list) + 1)) self.im_list.append(im) def get_new_size(self): max_width = 0 total_height = 0 # 計(jì)算合成后圖片的寬度(以最寬的為準(zhǔn))和高度 for img in self.im_list: width, height = img.size if width > max_width: max_width = width total_height += height return max_width, total_height def image_merge(self, ): if len(self.im_list) > 1: max_width, total_height = self.get_new_size() # 產(chǎn)生一張空白圖 new_img = Image.new('RGB', (max_width - 15, total_height), 255) x = y = 0 for img in self.im_list: width, height = img.size new_img.paste(img, (x, y)) y += height new_img.save(self.save_path) print('截圖成功:', self.save_path) else: obj = self.im_list[0] width, height = obj.size left, top, right, bottom = 0, 0, width, height box = (left, top, right, bottom) region = obj.crop(box) new_img = Image.new('RGB', (width, height), 255) new_img.paste(region, box) new_img.save(self.save_path) print('截圖成功:', self.save_path) def reedit_image(self, path): obj = Image.open(path) width, height = obj.size left, top, right, bottom = 0, height - self.over_flow_size, width, height box = (left, top, right, bottom) region = obj.crop(box) return region class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle('易哈佛') self.temp_height = 0 self.setWindowFlag(Qt.WindowMinMaxButtonsHint, False) # 禁用最大化,最小化 # self.setWindowFlag(Qt.WindowStaysOnTopHint, True) # 窗口頂置 self.setWindowFlag(Qt.FramelessWindowHint, True) # 窗口無(wú)邊框 def urlScreenShot(self, url): self.browser = QWebEngineView() self.browser.load(QUrl(url)) geometry = self.chose_screen() self.setGeometry(geometry) self.browser.loadFinished.connect(self.check_page) self.setCentralWidget(self.browser) def get_page_size(self): size = self.browser.page().contentsSize() self.set_height = size.height() self.set_width = size.width() return size.width(), size.height() def chose_screen(self): width, height = 750, 1370 desktop = QApplication.desktop() screen_count = desktop.screenCount() for i in range(0, screen_count): rect = desktop.availableGeometry(i) s_width, s_height = rect.width(), rect.height() if s_width > width and s_height > height: return QRect(rect.left(), rect.top(), width, height) return QRect(0, 0, width, height) def check_page(self): p_width, p_height = self.get_page_size() self.page, self.over_flow_size = divmod(p_height, self.height()) if self.page == 0: self.page = 1 self.ssm = ScreenShotMerge(self.page, self.over_flow_size) self.timer = QTimer(self) self.timer.timeout.connect(self.exe_command) self.timer.setInterval(400) self.timer.start() def exe_command(self): if self.page > 0: self.screen_shot() self.run_js() elif self.page < 0: self.timer.stop() self.ssm.image_merge() self.close() elif self.over_flow_size > 0: self.screen_shot() self.page -= 1 def run_js(self): script = """ var scroll = function (dHeight) { var t = document.documentElement.scrollTop var h = document.documentElement.scrollHeight dHeight = dHeight || 0 var current = t + dHeight if (current > h) { window.scrollTo(0, document.documentElement.clientHeight) } else { window.scrollTo(0, current) } } """ command = script + '\n scroll({})'.format(self.height()) self.browser.page().runJavaScript(command) def screen_shot(self): screen = QApplication.primaryScreen() winid = self.browser.winId() pix = screen.grabWindow(int(winid)) name = '{}/temp.png'.format(self.ssm.root_path) pix.save(name) self.ssm.add_im(name) if __name__ == '__main__': url = 'http://blog.sina.com.cn/lm/rank/focusbang//' app = QApplication(sys.argv) win = MainWindow() win.urlScreenShot(url) win.show() app.exit(app.exec_())
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中參數(shù)打包和解包的實(shí)現(xiàn)
在Python中,打包和解包參數(shù)是一種操作方式,可以將多個(gè)參數(shù)打包成一個(gè)元組或字典,也可以將一個(gè)元組或字典解包成多個(gè)參數(shù),本文就來(lái)介紹一下如何使用2023-09-09詳解python實(shí)現(xiàn)交叉驗(yàn)證法與留出法
這篇文章主要介紹了詳解python實(shí)現(xiàn)交叉驗(yàn)證法與留出法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python中使用socks5設(shè)置全局代理的方法示例
這篇文章主要介紹了Python中使用socks5設(shè)置全局代理的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04python使用for循環(huán)和海龜繪圖實(shí)現(xiàn)漂亮螺旋線
這篇文章主要為大家介紹了python使用for循環(huán)和海龜繪圖實(shí)現(xiàn)漂亮螺旋線實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06Python使用SQLAlchemy模塊實(shí)現(xiàn)操作數(shù)據(jù)庫(kù)
SQLAlchemy 是用Python編程語(yǔ)言開(kāi)發(fā)的一個(gè)開(kāi)源項(xiàng)目,它提供了SQL工具包和ORM對(duì)象關(guān)系映射工具,使用SQLAlchemy可以實(shí)現(xiàn)高效和高性能的數(shù)據(jù)庫(kù)訪問(wèn),下面我們就來(lái)學(xué)習(xí)一下SQLAlchemy模塊的具體應(yīng)用吧2023-11-11python數(shù)據(jù)可視化Seaborn畫(huà)熱力圖
這篇文章主要介紹了數(shù)據(jù)可視化Seaborn畫(huà)熱力圖,熱力圖的想法其實(shí)很簡(jiǎn)單,用顏色替換數(shù)字,下面我們來(lái)看看文章對(duì)操作過(guò)程的具體介紹吧,需要的小伙伴可以參考一下具體內(nèi)容,希望對(duì)你有所幫助2022-01-01python第三方庫(kù)easydict的使用實(shí)例詳解
在?Python?中當(dāng)我們需要訪問(wèn)字典中的元素的時(shí)候,我們需要使用類(lèi)似?a['example']?的形式來(lái)進(jìn)行使用,這個(gè)時(shí)候就可以使用 easydict 這個(gè)模塊了,今天通過(guò)本文給大家講解python第三方庫(kù)easydict的使用,感興趣的朋友跟隨小編一起看看吧2022-11-11