多线程PyQt5脚本时为什么出现此错误

时间:2019-07-25 16:43:34

标签: multithreading pyqt5

当我运行以下python代码时,出现以下错误。 有什么我想念的吗?

from bs4 import BeautifulSoup
import sys
import requests
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from threading import Thread

url = "https://www.booking.com/searchresults.fr.html?label=gen173nr-1FCAEoggI46AdIM1gEaE2IAQGYAQ24ARjIAQzYAQHoAQH4AQuIAgGoAgS4Ar3x5ukFwAIB&sid=a454e37209591e054b02e8917d61befe&tmpl=searchresults&checkin_month=8&checkin_monthday=1&checkin_year=2019&checkout_month=8&checkout_monthday=2&checkout_year=2019&class_interval=1&dest_id=-1456928&dest_type=city&dtdisc=0&from_sf=1&group_adults=1&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&postcard=0&raw_dest_type=city&room1=A&sb_price_type=total&shw_aparth=1&slp_r_match=0&src_elem=sb&srpvid=14466c78e41800bd&ss=Paris&ss_all=0&ssb=empty&sshis=0&ssne=Paris&ssne_untouched=Paris&order=review_score_and_price"


class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print('Load finished')

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()


class test(Thread):
    def __init__(self, number):
        Thread.__init__(self)
        self.number = number
        print(self.number)

    def run(self):
        """Code à exécuter pendant l'exécution du thread."""
        page = Page(url)
        soup = BeautifulSoup(page.html, 'html.parser')
        print(self.number)
        f = open("test" + self.number + ".html", "w")
        f.write(soup)
        f.close()



thread1 = test("1")
thread2 = test("2")

thread1.start()
thread2.start()

thread1.join()
thread2.join()

1 2 警告:QApplication不是在main()线程中创建的。 警告:QApplication不是在main()线程中创建的。 细分错误:11

1 个答案:

答案 0 :(得分:0)

作为警告状态,您正在主线程之外创建QApplication实例。对于任何Qt应用程序,仅存在一个QApplication对象,并且必须在创建任何其他Qt对象之前创建它。尝试这样的事情:

class Page(QWebEnginePage):
    def __init__(self, url):
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))

...

app = QApplication(sys.argv)

thread1 = test("1")
thread2 = test("2")

thread1.start()
thread2.start()

thread1.join()
thread2.join()

app.exec()