pyQt Python中的Q网络访问管理器(分段故障核心转储)

时间:2016-05-04 03:49:54

标签: python pyqt qwebview

我在python中使用pyQt开发了一个应用程序,并使用Web浏览器和表来显示浏览器请求附带的标头。 这是我的代码: -

import sys
from PyQt4.QtGui import QApplication, QTableWidget, QTableWidgetItem
from PyQt4.QtCore import QUrl  
from PyQt4.QtWebKit import QWebView, QWebPage
from PyQt4.QtGui import QGridLayout, QLineEdit, QWidget, QHeaderView
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest


class RequestsTable(QTableWidget):
    header = ["url", "status", "content-type","cookies","user_agent"]

    def __init__(self):
        super(RequestsTable, self).__init__()
        self.setColumnCount(5)
        self.setHorizontalHeaderLabels(self.header)
        header = self.horizontalHeader()
        header.setStretchLastSection(True)

    def update(self, data):
        last_row = self.rowCount()
        next_row = last_row + 1
        self.setRowCount(next_row)
        for col, dat in enumerate(data, 0):
            if not dat:
                 continue
            self.setItem(last_row, col, QTableWidgetItem(dat))

class Manager(QNetworkAccessManager):
    def __init__(self, table):
        QNetworkAccessManager.__init__(self)
        self.finished.connect(self._finished)
        self.table = table

    def _finished(self, reply):
        user_agent = str(reply.request().rawHeader("User-Agent"))
        headers = reply.rawHeaderPairs()
        headers = {str(k):str(v) for k,v in headers}
        content_type = headers.get("Content-Type")
        url = reply.url().toString()
        status =    reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        status, ok = status.toInt()
        cookies = headers.get("Set-Cookie")
        self.table.update([url, str(status),             content_type,cookies,user_agent])


if __name__ == "__main__":
    app = QApplication(sys.argv)

    grid = QGridLayout()
    browser = QWebView()
    browser.load(QUrl("http://www.indiatimes.com/"))
    def on_html_available():
        page = QWebPage()
        page.setNetworkAccessManager(manager)

        # problem is here
        browser.setPage(page)
        # if i dont use above line then it don't show any error but the headers don't get append in the table but if i use the above line it shows me the error segmentation fault

    browser.loadFinished.connect(on_html_available)
    requests_table = RequestsTable()
    manager = Manager(requests_table)
    grid.addWidget(browser, 3, 0)
    grid.addWidget(requests_table, 4, 0)
    main_frame = QWidget()
    main_frame.setLayout(grid)
    main_frame.show()
    sys.exit(app.exec_())

但上面的代码显示错误

"core dumped segmentation fault"? 

可能是什么问题?请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

它显示此错误,因为您再次在html上设置浏览器的页面,这是错误的,访问网络访问管理器您应首先获取管理器然后设置管理器页面,然后设置浏览器页面。如果你没有得到这个,请告诉我。