如何通过WebKit发送POST请求[PySide / PyQt]

时间:2012-09-10 05:33:01

标签: python pyqt pyside

使用PySide,如何从python代码中的webkit形式获取POST数据?

这是我的简单代码:

    import sys 
    from PySide.QtCore import * 
    from PySide.QtGui import QApplication 
    from PySide.QtWebKit import QWebView 

    html = """ 
    <html> 
    <body> 
        <form action="" method="post"><input name="test" /><input type="submit" value="submit"/></form>
    </body> 
    </html> 
    """ 


    if __name__ == '__main__': 
        app = QApplication(sys.argv) 
        view = QWebView() 
        frame = view.page().mainFrame() 
        view.setHtml(html) 
        view.show() 
        app.exec_()

我想获得我提交的字符串[key = test]

1 个答案:

答案 0 :(得分:2)

通过将自定义createRequest虚拟功能绑定到网络管理器,您可以看到发布的数据:

注意:使用 data.readAll()将清空顺序 QIODevice ,因此稍后webkit将无法访问数据,什么都不会发布。使用 data.peak(1024)  在不丢失数据的情况下具有相同的效果,唯一的不便是您必须传递您希望阅读的数据大小。

import sys 
from PySide.QtCore import * 
from PySide.QtGui import QApplication 
from PySide.QtWebKit import QWebView, QWebPage
from PySide.QtNetwork import QNetworkAccessManager

html = ''' 
<html> 
<body> 
    <form action="http://www.google.com" method="post"><input type="text" name="test" /><input type="submit" value="submit"/></form>
</body> 
</html> 
''' 

class Browser(object):

    def __init__(self):
        self.network_manager = QNetworkAccessManager()
        self.network_manager.createRequest = self._create_request

        self.web_page = QWebPage()
        self.web_page.setNetworkAccessManager(self.network_manager)

        self.web_view = QWebView()
        self.web_view.setPage(self.web_page)

        self.html_data = None

    def _create_request(self, operation, request, data):
        # data contains all the post data that is being added to the request
        # so you can look into it here
        print data.readAll()
        reply = QNetworkAccessManager.createRequest(self.network_manager,
                                                    operation,
                                                    request,
                                                    data)
        return reply

if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    browser = Browser() 
    frame = browser.web_page.mainFrame() 
    browser.web_view.setHtml(html) 
    browser.web_view.show() 
    app.exec_()