Python使用PyQt开发Web浏览器 QWebEngine 支持Flash

看这篇文章的读者一般是为了实现自动化测试,抓取信息之类的。
运气好不踩坑的话,PyQt真的简单。Qt目前推荐使用QWebEngine来实现Webkit。我碰到的第一个坑就是QWebEngine默认安装好后不支持Flash的,Windows下需要自己添加Pepper Flash Player Plugin Support支持。
参考https://doc.qt.io/qt-5/qtwebengine-features.html#pepper-plugin-api
测试代码如下
#!/bin/python3
#-*- coding: utf-8 -*-

def p(x): print(x)
def pt(x): print(x, type(x))

import re, sip, time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import threading
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, 
QLineEdit, QInputDialog)

from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *

class MyWebEngineView(QWebEngineView):
    def __init__(self, parent):
        super().__init__(parent)
        self.loop = 0
    def createWindow(self, webWindowType):
        self.loop += 1
        p('createWindow %02d' % (self.loop))
        return w.web
        
class MyWidget(QWidget):
    
    def __init__(self):
        super().__init__()
        QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
        QWebEngineSettings.globalSettings().setAttribute(QWebEngineSettings.FullScreenSupportEnabled, True)
        
        self.web = MyWebEngineView(self)
        self.web.resize(self.size())
        #self.web.load(QUrl("https://www.baidu.com/s?wd=1"))
        self.web.load(QUrl("http://www.youku.com"))
        self.web.show()

        self.init()    

    def resizeEvent(self, e):
        self.web.resize(self.size())

    def init(self):
        self.btn = QPushButton('按钮', self)
        self.btn.move(0, 0)
        self.btn.clicked.connect(self.btn_click)

        self.setGeometry(300, 300, 1000, 720)
        self.setWindowTitle('标题')        
        self.show()
        
    def js_callback(self, result):
        p("js_callback: " + str(result))

    def btn_click(self):
        self.web.page().runJavaScript('''
        window.pyqt;
        ''', self.js_callback)

def timeout():
    w.web.page().runJavaScript('''
        window.pyqt = "pyqt";
''');  

def urlChanged(x):
    p('urlChanged %s' % (x))    

if __name__ == '__main__':
    app = QApplication(sys.argv)

    w = MyWidget()
    w.web.urlChanged.connect(urlChanged)
    
    timer = threading.Timer(5, timeout)
    timer.start()
    sys.exit(app.exec_())
运行后会打开优酷,找部电影看看休息一下吧


发表于:2017-10-18 16:00:31

原文链接(转载请保留): http://www.multisilicon.com/blog/a23325837.html

友情链接: MICROIC
首页