基于PyQt4.QtWebKit的浏览器模拟类
# coding: utf8 import sys import os from time import time import code from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * class Pekit(): def __init__(self): self.user_agent = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100124 Firefox/3.6 (Swiftfox)' self.application = QApplication([]) self.webpage = QWebPage() self.webpage.userAgentForUrl = lambda url: self.user_agent self.webframe = self.webpage.currentFrame() self.webpage.javaScriptAlert = self._alert self.webpage.javaScriptConfirm = lambda frame, message: raw_input('==Confirm== (y/n): %s' % message) == 'y' self.webpage.javaScriptConsoleMessage = lambda string1, int1, string2: sys.stdout.write('==Message==: %s %d %s\n' % (string1, int1, string2)) self.webpage.javaScriptPrompt = lambda frame, message, defaultValue, result: raw_input('==Prompt== %s:' % message) or False self._load_status = 'init' self.webpage.connect(self.webpage, SIGNAL('loadFinished(bool)'), self._onLoadFinished) self.webpage.connect(self.webpage, SIGNAL('loadStarted()'), self._onLoadStarted) def load(self, url): self.webframe.load(QUrl(url)) self.wait_load() jsdir = os.path.dirname(__file__) jscode = open('%s/jquery.min.js' % jsdir, 'r').read() jscode += open('%s/jquery.simulate.js' % jsdir, 'r').read() jscode += "var _JQ = jQuery.noConflict();" self.js_noload(jscode) def js(self, js): self._load_status = 'start' self.webframe.evaluateJavaScript(js) def js_noload(self, js): self.webframe.evaluateJavaScript(js) def html(self): return unicode(self.webframe.toHtml()) def wait_load(self, least = 0, most = 300): start = time() while (self._load_status == 'start' and time() - start < most) or time() - start < least: self.application.processEvents() def _onLoadFinished(self, status): if status: self._load_status = 'end' def _onLoadStarted(self): self._load_status = 'start' def _alert(self, frame, message): print "==Alert== %s" % unicode(message)
参考了这个项目的代码:http://code.google.com/p/spynner/
谢谢你的留言,我去研究一下spynner
楼主是暨南大学的?
对啊
其实你怎么知道的?
google到了 FunShow 暨南风暨南大学| 学生论坛
原来如此。那个论坛现在就我在维护,,