浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

基于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/

2010年03月28日 | Posted in: 不分类只打TAG | 6 Comments »

6 Responses to “基于PyQt4.QtWebKit的浏览器模拟类”

  1. wong2 说道:

    谢谢你的留言,我去研究一下spynner

  2. wong2 说道:

    楼主是暨南大学的?

posted on 2012-02-06 18:14  lexus  阅读(1752)  评论(0编辑  收藏  举报