Python实现网页截图:PyQt4与Selenium两种方案详解
本文介绍Python实现网页截图的两种方法。方法一利用PyQt4的QtWebKit组件,通过QWebView加载页面并保存为图片,需注意字体像素警告及32/64位安装包下载。方法二使用Selenium库驱动Firefox浏览器,需配合geckodriver.exe使用,并提供了相应的pip安装命令及路径配置说明。
本文分享Python实现网页截图的具体实例,供读者参考学习。
方案一:基于PyQt4的QtWebKit组件
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import os.path
from PyQt4 import QtGui,QtCore,QtWebKit
class PageShotter(QtGui.QWidget):
def __init__(self,url,filename,parent=None):
QtGui.QWidget.__init__(self,parent)
self.url = url
self.filename = filename
self.webpage = None
def shot(self):
webview = QtWebKit.QWebView(self)
webview.load(QtCore.QUrl(self.url))
self.webpage = webview.page()
self.connect(webview,QtCore.SIGNAL("loadFinished(bool)"),self.save_page)
def save_page(self,finished):
#print finished
if finished:
print u"开始截图!"
size = self.webpage.mainFrame().contentsSize()
print u"页面宽:%d,页面高:%d" % (size.width(),size.height())
self.webpage.setViewportSize(QtCore.QSize(size.width()+16,size.height()))
img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
painter = QtGui.QPainter(img)
self.webpage.mainFrame().render(painter)
painter.end()
filename= self.filename;
if img.save(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
print u"截图完毕:%s" % filepath
else:
print u"截图失败";
else:
print u"网页加载失败!"
self.close()
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
shotter = PageShotter("https://www.jb51.net/", 'shot.png')
shotter.shot()
sys.exit(app.exec_())
程序运行后的控制台输出如下:
QFont::setPixelSize: Pixel size <= 0 (0) 开始截图! 页面宽:1058,页面高:9819 截图完毕:C:\py\jb51PyDemo\src\Demo\shot.png
注意事项:
若使用Python2的32位操作系统,可在此下载对应安装包:https://www.jb51.net/softs/548192.html 若使用64位操作系统,可在此下载对应的PyQt安装包:https://www.jb51.net/softs/548197.html
对于Python3环境,可直接通过pip命令安装PyQt5库,例如执行:
pip3 install PyQt5-sip
方案二:基于Selenium库
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
from selenium import webdriver
browser = webdriver.Firefox()
browser.set_window_size(1055, 800)
browser.get("https://www.jb51.net/")
browser.find_element_by_id("idClose").click()
time.sleep(5)
browser.save_screenshot("shot.png")
browser.quit()
补充说明:selenium库同样可通过pip命令进行安装:
pip install selenium
此外,使用Selenium时还需下载geckodriver以驱动第三方浏览器。针对Selenium3.x版本,需使用geckodriver驱动Firefox,因此需要下载geckodriver.exe文件,下载地址为:https://github.com/mozilla/geckodriver/releases
下载完成后,将geckodriver.exe放置于C:\Python27目录下(请确认环境变量path中已包含C:\Python27路径)。
如需了解更多Python相关内容,可查阅本站专题:《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。
希望上述内容能对您的Python编程有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









