方案说明

功能要求:实现网页加载后将页面截取成长图片
涉及模块:PyQT5 PIL

逻辑说明:

1:完成窗口设置,利用PyQT5 QWebEngineView加载网页地址,待网页加载完成后,调用check_pag;

class MainWindow(QMainWindow):def __init__(self, parent=None):super(MainWindow, self).__init__(parent)self.setWindowTitle('易哈佛')self.temp_height = 0self.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)  # 禁用最大化,最小化# self.setWindowFlag(Qt.WindowStaysOnTopHint, True)  # 窗口顶置self.setWindowFlag(Qt.FramelessWindowHint, True)  # 窗口无边框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, 1370desktop = 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:收集页面高度,并计算分次截屏的次数和余量高度;实例化图片合并工具,设置定时器,超时信号发出后,执行exe_command;

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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 = 1self.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用来控制截图次数,并在每次截图完成后控制网页向下滑屏幕的高度;所有的页面都已截取时,完成图片合并。

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 -= 1def run_js(self):script = """var scroll = function (dHeight) {var t = document.documentElement.scrollTopvar h = document.documentElement.scrollHeightdHeight = dHeight || 0var current = t + dHeightif (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在每次截图完成后将图片保存,并将图片对象由图片合并根据保存到列表中。

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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:截图合并工具,在每次截图完成后将图片对象保存,完成余量截图的重绘和截图的合并。

class ScreenShotMerge():def __init__(self, page, over_flow_size):self.im_list = []self.page = pageself.over_flow_size = over_flow_sizeself.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 = 0total_height = 0# 计算合成后图片的宽度(以最宽的为准)和高度for img in self.im_list:width, height = img.sizeif width > max_width:max_width = widthtotal_height += heightreturn max_width, total_heightdef image_merge(self, ):if len(self.im_list) > 1:max_width, total_height = self.get_new_size()# 产生一张空白图new_img = Image.new('RGB', (max_width - 15, total_height), 255)x = y = 0for img in self.im_list:width, height = img.sizenew_img.paste(img, (x, y))y += heightnew_img.save(self.save_path)print('截图成功:', self.save_path)else:obj = self.im_list[0]width, height = obj.sizeleft, top, right, bottom = 0, 0, width, heightbox = (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.sizeleft, top, right, bottom = 0, height - self.over_flow_size, width, heightbox = (left, top, right, bottom)region = obj.crop(box)return region

截图功能完整代码

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
#遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
#寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
from PIL import Image
from pathlib import Pathclass ScreenShotMerge():def __init__(self, page, over_flow_size):self.im_list = []self.page = pageself.over_flow_size = over_flow_sizeself.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 = 0total_height = 0# 计算合成后图片的宽度(以最宽的为准)和高度for img in self.im_list:width, height = img.sizeif width > max_width:max_width = widthtotal_height += heightreturn max_width, total_heightdef image_merge(self, ):if len(self.im_list) > 1:max_width, total_height = self.get_new_size()# 产生一张空白图new_img = Image.new('RGB', (max_width - 15, total_height), 255)x = y = 0for img in self.im_list:width, height = img.sizenew_img.paste(img, (x, y))y += heightnew_img.save(self.save_path)print('截图成功:', self.save_path)else:obj = self.im_list[0]width, height = obj.sizeleft, top, right, bottom = 0, 0, width, heightbox = (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.sizeleft, top, right, bottom = 0, height - self.over_flow_size, width, heightbox = (left, top, right, bottom)region = obj.crop(box)return regionclass MainWindow(QMainWindow):def __init__(self, parent=None):super(MainWindow, self).__init__(parent)self.setWindowTitle('易哈佛')self.temp_height = 0self.setWindowFlag(Qt.WindowMinMaxButtonsHint, False)  # 禁用最大化,最小化# self.setWindowFlag(Qt.WindowStaysOnTopHint, True)  # 窗口顶置self.setWindowFlag(Qt.FramelessWindowHint, True)  # 窗口无边框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, 1370desktop = 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 = 1self.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 -= 1def run_js(self):script = """var scroll = function (dHeight) {var t = document.documentElement.scrollTopvar h = document.documentElement.scrollHeightdHeight = dHeight || 0var current = t + dHeightif (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_())

Python实现网页截图相关推荐

  1. Python实现网页截图,附带完整代码

    Python实现网页截图,附带完整代码 在现代化的互联网时代,我们经常需要对网页进行截图以便于保存.共享以及其他种种用途.Python是一种功能强大的编程语言,可以帮助我们轻松地实现网页截图功能.本文 ...

  2. python抓取网页数据并截图_python实现自动网页截图并裁剪图片

    本文实例为大家分享了python自动网页截图并裁剪图片的具体代码,供大家参考,具体内容如下 代码: # coding=utf-8 import time from selenium import we ...

  3. linux下使用python截图_linux多线程网页截图-python

    上一篇中( linux多线程网页截图-shell ),使用shell多进程对大量的网站截图,大大减少了截图的时间.但慢慢的也发现了这种方式的弊端:每个进程分配的网站数量是相等的,有些进程截图较快,有些 ...

  4. python实现网页长截图

    python实现网页长截图 实现思路 使用工具和第三方库 参考内容网址 具体代码案例 实现思路 获取到所需内容 截图.移动.截图.移动- 拼接 使用工具和第三方库 Python.Pycharm PIL ...

  5. Python将网页转化为PDF(python网页自动长截图)

    初次实践:python网页自动截图 步骤如下: (1) 安装python selenium 库,推荐使用pip快速安装最新版本 pip install selenium (2) 检查Chrome浏览器 ...

  6. 网页截图并自动放入word文档【python】

    这里写自定义目录标题 使用场景 准备环境 实现逻辑 引入包 截图模块 访问mysql数据库,获取标题和网址 截图并保存为word 使用场景 从mysql数据库中读取需求标题和对应网页传参,提供网页截图 ...

  7. python获取网页元素坐标_html网页元素在屏幕上的坐标获取

    今天在用python调用IE获取html网页元素在屏幕上的坐标,当然为了截图啦,(*^__^*) 嘻嘻-- xtop=ie.document.forms[i].elements[j].getBound ...

  8. 实用小技巧---如何给全部网页截图

    相信大家在平时学习和工作的时候,都少不了要对网页截图.可是,如果使用一般传统的截图方法:QQ截图或者微信截图,很难做到对一个网页的全部页面截图.如下图: 因为这些截图方法,只能对电脑屏幕现在展示出来的 ...

  9. phantomjs实现免费在线网页截图工具-toolfk程序员在线工具网

    本文要推荐的[ToolFk]是一款程序员经常使用的线上免费测试工具箱,ToolFk 特色是专注于程序员日常的开发工具,不用安装任何软件,只要把内容贴上按一个执行按钮,就能获取到想要的内容结果.Tool ...

最新文章

  1. 值得一读的《框架设计(第2版):CLR Via C#》
  2. 奇怪吸引子---NoseHoover
  3. IE6不支持PNG图片透明效果的完美解决方案(完善版)
  4. java 开发帮助_java的简单编程请帮助
  5. CTS(20)---CTS测试框架 -- V2版本
  6. matlab贝塞尔函数的根,matlab画贝塞尔函数根分布的曲线图
  7. php动态网页设计制作作业成品
  8. 蓝桥杯2021年第十二届C++省赛第九题-双向排序
  9. 常用SQL语句(1)
  10. Python汉诺塔递归算法实现
  11. Java那些不为人知的技巧
  12. 吉林大学计算机专业研究生导师,吉林大学计算机科学与技术学院导师教师简介-张晋东...
  13. python京东抢购软件_福利来了,python 京东抢购茅台脚本(亲测可用)
  14. 计算机毕业论文致谢信范文,论文致谢信10篇
  15. 傅里叶变换的理解-从正弦信号到傅里叶
  16. jQuery选择器(二)
  17. 线程 、GCD、NSOperation用法总结,重复下载,线程之间的通信
  18. 菜谱更新:平菇烧豆腐。
  19. 每天15min-HTML5(1)-学习方法
  20. Day13 推导式、推导式试题、集合推导式、生成器函数、生成器表达式

热门文章

  1. jQuery多库共存问题解决方法
  2. MyBatis学习总结(七)——Mybatis缓存
  3. Linux下find命令的用法
  4. 绘制对象iPhone开发基础教程 笔记
  5. Firefox 4网页演示:宣布Web O’Wonder的奇迹
  6. python中locals函数_Python locals()函数
  7. 宏碁e5572g57mx加固态_宏基e5572g57mx怎么拆机
  8. win10北通手柄没反应_《动物森友会》怎么玩出新花样?北通宙斯游戏手柄宏玩法了解下...
  9. 卡号身份证过期的影响
  10. ABAP 生成ZIP压缩文件的代码