欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用python对整个网页进行截图

程序员文章站 2022-05-31 21:29:05
方法一、使用PyQt4的QtWebKit组件 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 ......

方法一、使用pyqt4的qtwebkit组件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/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("")
    shotter = pageshotter("", 'shot.png')
    shotter.shot()
    sys.exit(app.exec_())

 

 

方法二、使用selenium

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import time
from selenium import webdriver
 
browser = webdriver.firefox()
browser.set_window_size(1055, 800)
browser.get("")
browser.find_element_by_id("idclose").click()
time.sleep(5)
 
browser.save_screenshot("shot.png")
browser.quit()