#coding=utf-8 __author__ = 'ds' from PyQt4.QtCore import * from PyQt4.QtWebKit import * from PyQt4.QtNetwork import * from PyQt4.QtGui import * import sys,os class Page(QWebPage): def __init__(self, parent = None): super(Page, self).__init__(parent) #设置连接代理模式 #self.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) #连接点击,加载URL地址 self.linkClicked.connect(self.onLinkClick) self.loadFinished.connect(self.onLoadFinish) def onLinkClick(self, url): self.mainFrame().load(url) @staticmethod def doMouseClick(obj, pos): # mouse down evt = QMouseEvent(QEvent.MouseButtonPress, pos, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QApplication.sendEvent(obj, evt) # mouse up evt = QMouseEvent(QEvent.MouseButtonRelease, pos, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QApplication.sendEvent(obj, evt) def onLoadFinish(self): css = 'a[class="mnav"][name="tj_trmap"]' js = 'this.click();' root = self.mainFrame().documentElement() link_map = root.findFirst(css) if link_map: #方案1:可能不会起作用,除了按钮以为并非对所有的链接都支持 #link_map.evaluateJavaScript(js) #方案2,直接做鼠标点击的模拟,对隐藏控件不行 #self.doMouseClick(self, link_map.geometry().center()) #方案3,使用event进行处理,只要支持事件,就可以(除非禁掉) link_map.evaluateJavaScript(""" //鼠标点击 var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); //将该事件分发给自己进行接收 this.dispatchEvent(e); //直接使用事件处理很好用 //this.addEventListener('click', function(){ // alert('test'); //}); """) print('Javascript Evaluated.') app = QApplication(sys.argv) QNetworkProxyFactory.setUseSystemConfiguration(True) mv = QWebView() mv.setWindowTitle(u'Javascript浏览器') mv.setPage(Page()) mv.show() mv.load(QUrl('http://www.baidu.com')) app.exec_()