1

使用 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]

4

1 回答 1

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_()
于 2012-09-14T06:50:47.713 回答