我想使用多线程来运行多个QWebview来获取数据。但不知道如何使用qwebview实现线程。这里我写了一些代码:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
from PyQt4 import QtCore, QtGui
from lxml import etree,html
from PyQt4.QtCore import Qt
import sys
class Form(QWidget):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setMouseTracking(True)
vbox = QVBoxLayout()
self.browser = QWebView()
self.browser.connect(self.browser,SIGNAL('loadFinished(bool)'),self.loadFinished)
#vbox.addWidget(self.browser)
self.browser.load(QtCore.QUrl("http://www.google.com"))
self.browser_tabs = QTabWidget()
self.browser_tabs.setTabPosition(QTabWidget.South)
b1_tab = QWidget()
d = QHBoxLayout()
d.addWidget(self.browser)
b1_tab.setLayout(d)
self.browser_tabs.addTab(b1_tab,"browser0")
vbox.addWidget(self.browser_tabs)
self.setLayout(vbox)
def loadFinished(self,ok):
print ok
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
ex.setGeometry(150, 100, 1024, 770)
#ex.showMaximized()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
您可以使用选项卡小部件打开多个浏览器。
为Form类定义一个新函数。并使用thread.start_new_thread(函数名,参数())。
import thread
class Form(QWidget):
...
def addNewTab(self, newUrl, tabIndex):
new_browser = QWebView()
new_browser.connect(self.browser,SIGNAL('loadFinished(bool)'),self.loadFinished)
new_browser.load(QtCore.QUrl(newUrl))
new_tab = QWidget()
d = QHBoxLayout()
d.addWidget(new_browser)
new_tab.setLayout(d)
self.browser_tabs.addTab(new_tab, "browser" + str(tabIndex))
# Do your scraping here
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
ex.setGeometry(150, 100, 1024, 770)
thread.start_newThread(ex.addNewTab, (someUrl1, 1))
thread.start_newThread(ex.addNewTab, (someUrl2, 2))
thread.start_newThread(ex.addNewTab, (someUrl3, 3))
sys.exit(app.exec())