如何获取 QWebEngineView 中加载的页面的 html

How to get html of a page loaded in QWebEngineView

我正在尝试获取 HTML 在 PyQT5 QWebEngineView 中加载的页面。这是一个简单的例子:

import sys
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWidgets import *


def callback_function(html):
    print(html)


def on_load_finished():

    web.page().runJavaScript("document.getElementsByTagName('html')[0]", callback_function)


app = QApplication(sys.argv)
web = QWebEngineView()
web.load(QUrl("https://whosebug.com"))
web.show()
web.loadFinished.connect(on_load_finished)

sys.exit(app.exec_())

我希望能够从 runJavaScript() 调用中 return html 但我在回调函数中得到一个空白。

我的代码中有什么不正确的地方,还有哪些替代方法可用于获取页面的 HTML?

使用我的 编写的 C++ 并将解决方案转换为 Python:

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication


def callback_function(html):
    print(html)


def on_load_finished():
    web.page().runJavaScript("document.documentElement.outerHTML", callback_function)


app = QApplication(sys.argv)
web = QWebEngineView()
web.load(QUrl("https://whosebug.com"))
web.show()
web.resize(640, 480)
web.loadFinished.connect(on_load_finished)

sys.exit(app.exec_())

更新:

你的问题是 getElementsByTagName() returns 一个 js 元素列表,并且该元素无法导出到 python,你应该做的是获取 innerHTML:

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication


def callback_function(html):
    print(html)


def on_load_finished():
    web.page().runJavaScript(
        "document.getElementsByTagName('html')[0].innerHTML", callback_function
    )
    # or document.getElementsByTagName('html')[0].outerHTML


app = QApplication(sys.argv)
web = QWebEngineView()
web.load(QUrl("https://whosebug.com"))
web.show()
web.resize(640, 480)
web.loadFinished.connect(on_load_finished)

sys.exit(app.exec_())