【发布时间】:2016-11-11 05:57:08
【问题描述】:
我正在尝试为通过 JavaScript 加载的网页编写 Beautifulsoup 爬虫,Beautifulsoup 无法解析该网页。为了解决这个问题,我按照this tutorial 使用 QtWebkit 渲染页面,然后使用 Beautifulsoup 从生成的 HTML 中提取页面中的所有 href。
但是,页面抓取非常大,在完成获取这些链接之前,它会抛出错误“QThread: Destroyed while thread is still running”。许多人已经发布了有关此错误的问题并收到了答案,但是这些都是针对以 PyQT 为应用程序核心的更复杂的项目,因此这些回复假定您熟悉该库并且我在尝试应用它们时遇到了真正的麻烦我的情况。
似乎我需要通过将线程保存在变量中来防止线程被垃圾收集,但正确的方法却让我望而却步。
这是我的代码:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from bs4 import BeautifulSoup
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'http://www.lolesports.com/en_US/msi/msi_2016/schedule/default'
r = Render(url)
result = r.frame.toHtml()
soup = BeautifulSoup(result, "html.parser")
for link in soup.find_all('a'):
print(link.get('href'))
【问题讨论】:
-
QApplication.exec_() 阻塞,直到应用程序退出/中止。不要把它放在init中。
标签: python multithreading pyqt beautifulsoup web-crawler