• 基于PyQt4.QtWebKit的浏览器模拟类


    基于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 说道:

      楼主是暨南大学的?

  • 相关阅读:
    其他
    Win10
    Win10
    面向对象与设计模式
    Git
    Java
    Git
    Git
    Git
    一、I/O操作(File文件对象)
  • 原文地址:https://www.cnblogs.com/lexus/p/2340494.html
Copyright © 2020-2023  润新知