1. 程式人生 > >Pyqt 瀏覽器自動填充input框小demo

Pyqt 瀏覽器自動填充input框小demo

pyqt 瀏覽器自動登入,需要自動填充input框。

核心程式碼,如果login模組在主frame下的:

mainframe = self.page().currentFrame()
doc = mainframe.documentElement()
user_elem = doc.findFirst('input[name=WebUserNO]')
user_elem.evaluateJavaScript("this.value='ouyang';")

核心程式碼,如果login模組在子frame下的:
mainframe = self.page().currentFrame()
children = mainframe.childFrames()
loginframe = children[0]
doc = loginframe.documentElement()
user_elem = doc.findFirst('input[name=WebUserNO]')
user_elem.evaluateJavaScript("this.value='ouyang';")

效果:


全部程式碼:

# #coding:utf-8  
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtWebKit import*
from PyQt4 import QtCore, QtGui
from PyQt4 import uic
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
import sys
from IPython import embed
import Image
import unicodedata

reload(sys)
sys.setdefaultencoding('utf-8')

#解決QString中文亂碼
QTextCodec.setCodecForCStrings(QTextCodec.codecForName("utf-8"))

#控制檯
class MyConsole(QWidget):
    def __init__(self,parent):
        QWidget.__init__(self)
        self.parent = parent
        self.initUI()
        
    #初始化UI    
    def initUI(self):
        self.gridlayout = QtGui.QGridLayout()
         
        #設定出20 x 20 的格局
        for i in range(20):
            self.gridlayout.setColumnStretch(i,1)
            self.gridlayout.setRowStretch(i,1)

        lb1 = QLabel(u'賬戶:')
        lb2 = QLabel(u'密碼:')
        self.userEntry = QLineEdit()
        self.passEntry = QLineEdit()
        self.passEntry.setEchoMode(QLineEdit.Password)
        self.loginBtn = QtGui.QPushButton(u"登入")
        self.loginBtn.setFixedSize(40,20)
        self.connect(self.loginBtn, QtCore.SIGNAL('clicked()'), self.onLoginButton)
        
        self.gridlayout.addWidget(lb1, 0, 0)
        self.gridlayout.addWidget(lb2, 1, 0)
        self.gridlayout.addWidget(self.userEntry, 0, 1,1,3)
        self.gridlayout.addWidget(self.passEntry, 1, 1,1,3)
        self.gridlayout.addWidget(self.loginBtn, 0, 4,1,2)
        
        self.setLayout(self.gridlayout)   
  
    #響應登入按鈕
    def onLoginButton(self):
            
        #下載網頁
        self.bro.savePageHtml()
        
        username = self.userEntry.text()
        password = self.passEntry.text()
        QtGui.QMessageBox.about(self, username+u'登入成功', u"密碼是:"+password)
        tmpstr = username+u'登入成功!\n' + u"密碼是:"+password
        print str(tmpstr).decode('utf-8')

#瀏覽器        
class MyBrowser(QWebView):
    def __init__(self):
        QWebView.__init__(self)
        self.webpage = QWebPage(self)
        self.setPage(self.webpage)
        self.url = 'http://jiaowu.dlufl.edu.cn/'
        self.webpage.javaScriptAlert =  self._javascript_alert  #過載 alert函式
        self.load(QtCore.QUrl(self.url))
        QtCore.QObject.connect(self,QtCore.SIGNAL('loadFinished(bool)'),self.do_loadFinished)   
        
        
    #重寫js alert,讓它自動確定
    def _javascript_alert(self, webframe, message):
        return
    
       
    #頁面載入完成的處理函式
    def do_loadFinished(self):
        #通過chrome 原始碼發現loginframe是主frame的第0個子frame
        mainframe = self.page().currentFrame()
        children = mainframe.childFrames()
        loginframe = children[0]
        
        #獲取document元素
        doc = loginframe.documentElement()
        
        #列印網頁title
        print 'Page load..',str(mainframe.title()).decode('utf-8'),"##"
        
        #截圖+裁剪圖
        self.savePageImage()
        
        #下載頁面
        self.savePageHtml()
        
        #使用者名稱密碼
        user_elem = doc.findFirst('input[name=WebUserNO]')
        user_elem.evaluateJavaScript("this.value='ouyang';")
        
        pass_elem = doc.findFirst('input[name=Password]')
        pass_elem.evaluateJavaScript("this.type='text';")
        pass_elem.evaluateJavaScript("this.value='qiqi';")
        
        #驗證碼
        value = '9999'
        checkcode_elem = doc.findFirst('input[name=Agnomen]')
        checkcode_elem.evaluateJavaScript("this.value='"+value+"';"); 
        a = doc.findAll('input[name=Agnomen]')
        
        
    #截圖    
    def savePageImage(self):
        size = self.page().currentFrame().contentsSize()
        img = QtGui.QImage(size, QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(img)
        self.page().currentFrame().render(painter)
        painter.end()
        fileName= "./shot.png";
        if img.save(fileName):
            #裁剪驗證碼所在區域圖片
            im = Image.open(fileName) #開啟圖片控制代碼  
            box = (85,260,135,275) #設定裁剪區域  
            region = im.crop(box)  #裁剪圖片,並獲取控制代碼region  
            region.save('./checkcode.png',) #儲存圖片
        else:
            print u"截圖失敗";
        
    #下載頁面
    def savePageHtml(self):
        self.getMainFrame()
        self.getChildFrames()
    
    #獲取主框架HTML
    def getMainFrame(self):
        frame = self.page().mainFrame()
        with open('main-html.txt','w') as file:
            file.write(frame.toHtml())
    
    #獲取子框架HTML        
    def getChildFrames(self):
        frame = self.page().mainFrame()
        children = frame.childFrames()
        fT = []
        
        for x in range(len(children)):
            with open(str(x)+'-html.txt','w') as file:
                file.write(children[x].toHtml())
            
     
            
class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        tabs = QtGui.QTabWidget(self)
        
        
        #tab1
        tab1 = QtGui.QWidget() 
        vBox1 = QtGui.QVBoxLayout()
        console = MyConsole(self)
        vBox1.addWidget(console)
        tab1.setLayout(vBox1)
        
        #tab2
        tab2 = QtGui.QWidget()
        web = MyBrowser() 
        
        vBox2 = QtGui.QVBoxLayout()
        vBox2.addWidget(web)
        tab2.setLayout(vBox2)
        
        
        tabs.addTab(tab1,u"控制檯")
        tabs.addTab(tab2,u"瀏覽器")
        
        tabs.resize(500, 350)
        self.resize(500, 350)
        
        #禁止最大化
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    app.connect( app, SIGNAL( "lastWindowClosed()" ), app.quit);
    win = MainWindow()
    sys.exit(app.exec_())
 
if __name__ == '__main__':
    main()