Pycharm 上的 PyQt5,未使用的模块

PyQt5 on Pycharm, Modules not used

正在编写一个 Python 脚本来在网页有 运行 个 JavaScript 之后抓取网页。我意识到我需要 运行 的 JS,因为使用请求不会返回任何数据。我找到了似乎是我的解决方案 here 但我仍然遇到一些问题。

首先,该教程使用 PyQt4,我已经从项目解释器安装并尝试了 PyQt 4 和 5 的多个版本,但仍然找不到解决方案。这是相关代码:

import PyQt5.QtWebEngineWidgets
import PyQt5.QtCore
import PyQt5.QtWebEngine
import PyQt5.QtWebEngineCore


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 _load_finished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()

QWebpage、QApplication、QUrl调用均有'Unresolved Reference'错误,4条PyQt5导入语句也均有'Unused Import Statement'指示。我已经尝试了几个小时来解决这些问题,卸载并重新安装了 PyQt 并在互联网上搜索了几次

任何建议都很棒,谢谢!

你的导入不正确,在 python 中有很多方法可以做到:在你的情况下你可以这样:

1.from package import class


import sys

from PyQt5.QtCore import QUrl
from PyQt5.QtWebKitWidgets import QWebPage
from PyQt5.QtWidgets import QApplication


# Take this class for granted.Just use result of rendering.
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://pycoders.com/archive/'
r = Render(url)
result = r.frame.toHtml()
print(result)
  1. import package,那么你应该使用每个元素作为 package.class:

import sys
from PyQt5 import QtWebKitWidgets, QtCore, QtWidgets


class Render(QtWebKitWidgets.QWebPage):
    def __init__(self, url):
        self.app = QtWidgets.QApplication(sys.argv)
        QtWebKitWidgets.QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QtCore.QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()


url = 'http://pycoders.com/archive/'
r = Render(url)
result = r.frame.toHtml()
print(result)

如果您正在使用 pycharm,有一种非常简单的方法可以让 pycharm 为您正确导入包,为此您必须将点放在生成错误的单词上方并执行 Ctrl+M

注意:如果您正在使用 windows,您将无法使用这些模块,因为 Qt 和 PyQt,请使用 chromium,而且它们似乎有问题 Windows.