我需要获取动态内容,该内容由 ajax js 调用加载。
我真的不知道如何使用 PyQt,但我希望我能做到这一点。HTML是这样的:
<a href="#" id="id" onclick="A4J.AJAX.Submit('j_id0:j_id1:j_id110',event,{'similarityGroupingId':'j_id0:j_id1:j_id110:j_id582:0:j_id584'});return false;">NETHERLANDS</a>`
Run Code Online (Sandbox Code Playgroud)
我可以使用以下简单代码使用 PyQt 呈现页面:
def render(source_html):
import sys
from PyQt5.QtCore import QEventLoop
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
class Render(QWebEngineView):
def __init__(self, html):
self.html = None
self.app = QApplication(sys.argv)
QWebEngineView.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.setHtml(html)
while self.html is None:
self.app.processEvents(QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers | QEventLoop.WaitForMoreEvents)
self.app.quit()
def _callable(self, data):
self.html = data
def _loadFinished(self, result):
self.page().toHtml(self._callable)
return Render(source_html).html
import requests
sample_html = requests.get('https://riverbankcomputing.com/software/pyqt/').text
print(render(sample_html))
Run Code Online (Sandbox Code Playgroud)
我如何运行“onclick”并获取内容?
我正在尝试使用 Qt classesQWebEngineView并QWebChannel在 HTML 页面和 Python 脚本之间建立简单的连接。目标只是在单击foo()标题时执行<h2>。
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
html = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script>
var backend;
new QWebChannel(qt.webChannelTransport, function (channel) {
backend = channel.objects.backend;
});
document.getElementById("header").addEventListener("click", function(){
backend.foo();
});
</script>
</head>
<body> <h2 id="header">Header.</h2> </body>
</html>
'''
class HelloWorldHtmlApp(QWebEngineView):
def __init__(self):
super().__init__()
# setup a page with my …Run Code Online (Sandbox Code Playgroud) 我已经部分工作,但我面临几个困难:
1)看来QWebEnginePage需要QWebEngineView。(请参阅此处的 setView() 方法:https://code.woboq.org/qt5/qtwebengine/src/webenginewidgets/api/qwebenginepage.cpp.html)
2) QWebEngineView 除非可见,否则不会呈现。
3) 似乎没有任何方法可以检测视图的哪些区域受到了影响。
我想确认一下新 API 是否可以做到这一点?旧的 QT WebKit API 提供了一种实现此目的的方法。
我遵循了这个解决方案并且一开始工作得很好。
但是在我更改一次或QWebEngineView不关心它后,我无法再次更改代理。
原始代码包含的不止这些,所以我将它纯化为一个工作示例来演示我的问题
假设我们的ip是“xxxx”,proxy1的ip是“yyyy”,proxy2的ip是“zzzz”
当您运行示例代码时,您必须看到
但我得到了
那么,任何想法如何解决这个问题?
示例运行代码:(只需更改测试功能中的代理信息。您可以从这里尝试任何工作代理:http : //free-proxy.cz/en/)。
""" NODOC """
__author__ = 'ozgur'
__creation_date__ = '7.10.2020 14:04'
import sys
import time
from PyQt5 import QtNetwork
from PyQt5.QtCore import QMetaObject, QTimer, QUrl
from PyQt5.QtTest import QTest
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout
class RosaRafined(QMainWindow):
# noinspection PyUnusedLocal
def …Run Code Online (Sandbox Code Playgroud) 我有一个非常简单的应用程序WebEngineView,我只想将显示的小部件大小调整为 html 文件的内容。我期望它是 30 像素宽。相反,我的程序会打印QSize(0,0),更糟糕的是,小部件根本没有显示。
我在这里做错了什么?
#include <QWebEngineView>
#include <QApplication>
#include <QDebug>
#include <QWebEnginePage>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto view = new QWebEngineView;
QString html = "<html><body><div width=30px>Text</div></body></html>";
view->setHtml(html);
auto contentsSize=view->page()->contentsSize().toSize();
qDebug() << contentsSize;
view->setFixedSize(contentsSize);
view->show();
return app.exec();
}
Run Code Online (Sandbox Code Playgroud)
将我的 QWebEngineView 放入对话框仍然不起作用:
#include <QWebEngineView>
#include <QApplication>
#include <QDebug>
#include <QDialog>
#include <QHBoxLayout>
#include <QWebEnginePage>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto dialog = new QDialog;
dialog->setLayout(new QHBoxLayout);
auto …Run Code Online (Sandbox Code Playgroud) 我在 pyside2 中编写了一个应用程序,它在 QWebEngine 中打开了一个网页。
该网页有 2 个按钮,我不明白如何检测 pyside2 应用程序模块中的按钮点击,我需要对该按钮点击执行其他操作。
例子
下面是我的代码
from PySide2.QtWidgets import QApplication
from PySide2.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PySide2.QtCore import QUrl
class WebEnginePage(QWebEnginePage):
def __init__(self, *args, **kwargs):
QWebEnginePage.__init__(self, *args, **kwargs)
self.featurePermissionRequested.connect(self.onFeaturePermissionRequested)
def onFeaturePermissionRequested(self, url, feature):
if feature in (QWebEnginePage.MediaAudioCapture,
QWebEnginePage.MediaVideoCapture,
QWebEnginePage.MediaAudioVideoCapture):
self.setFeaturePermission(url, feature, QWebEnginePage.PermissionGrantedByUser)
else:
self.setFeaturePermission(url, feature, QWebEnginePage.PermissionDeniedByUser)
app = QApplication([])
view = QWebEngineView()
page = WebEnginePage()
page.profile().clearHttpCache()
view.setPage(page)
view.load(QUrl("https://test.webrtc.org/"))
view.show()
app.exec_()
Run Code Online (Sandbox Code Playgroud)
下面是输出:
现在我只想在用户单击“开始”按钮时关闭我的应用程序。
我想为QWebEngineView带有大图像的页面截取屏幕截图。当在红色背景下运行代码时正确呈现但图像不是。
在截取屏幕截图之前,如何确保页面已完全呈现?
from PySide2 import QtCore, QtWidgets, QtWebEngineWidgets
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
img { max-width:100%; max-height:100%; }
div { height: 270px; width: 540px; }
body { margin: 0; background-color: red; }
</style>
</head>
<body>
<div>
<img src="https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73751/world.topo.bathy.200407.3x5400x2700.png">
</div>
</body>
</html>
"""
class Capture(QtWebEngineWidgets.QWebEngineView):
def __init__(self, parent=None):
super(Capture, self).__init__(parent)
self.loadFinished.connect(self.save)
self.show()
self.resize(540, 270+5)
@QtCore.Slot(bool)
def save(self, isOk):
if not isOk:
print('Error')
return
self.grab().save('page.png', b'PNG')
if __name__ == '__main__':
app = QtWidgets.QApplication()
capture …Run Code Online (Sandbox Code Playgroud) 我正在使用 QtWebEngineWidgets,QtWebChannel创建 PyQt5 应用程序,它使用 HTML、CSS、JavaScript。
它工作正常,当我们以一般方式运行时,即, python main.py
导入 HTML 如下,
current_dir = os.path.dirname(os.path.realpath(__file__))
filename = os.path.join(current_dir, "index.html")
url = QtCore.QUrl.fromLocalFile(filename)
Run Code Online (Sandbox Code Playgroud)
导入 CSS、JavaScript 文件如下,
# in index.html
<link rel="stylesheet" href="styles.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_custom.js"></script>
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试.exe使用pyinstaller.
我从这里尝试过但没有成功。
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path …Run Code Online (Sandbox Code Playgroud) 如何在 PyQt5 应用程序中渲染 Markdown 文件?
在这里我读到我应该使用 QWebEngineView 而不是 QTextEdit,因为 QTextEdit 无法渲染外部图像。
在评论中有人引用了这个例子。然而,它是一个完整的 Markdown 文本编辑器,并且另外用 C++ 编写。我尝试将所需的部分翻译成Python,但我不太明白它是如何工作的。我只需要一个最小的例子。
我现在拥有的是以下内容:
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
import sys
app = QApplication(sys.argv)
web_widget = QWebEngineView()
webChannel = QWebChannel() # ?
page = QWebEnginePage() # ?
web_widget.setPage(page) # ?
my_url = QUrl("/index.html")
web_widget.load(my_url)
# now somehow replace the placeholder in the loaded html page with file contents?
file_url = QUrl("file.md")
# …Run Code Online (Sandbox Code Playgroud) 我正在使用以下命令在 C++ 应用程序中嵌入不和谐小部件QWebEngineView我正在使用;小部件工作一切正常,问题在于登录。
我可以从小部件登录我的不和谐帐户,但在登录窗口关闭并返回小部件后,我在控制台上收到以下错误:
js: Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'interest-cohort'.
js: Unrecognized Content-Security-Policy directive 'prefetch-src'.
js: Uncaught (in promise) function(){}
js: Unrecognized Content-Security-Policy directive 'prefetch-src'.
js: Unrecognized Content-Security-Policy directive 'prefetch-src'.
js: Uncaught (in promise) Error: Cannot find module './notosans-400-normalitalic.woff2'
js: Unrecognized Content-Security-Policy directive 'prefetch-src'.
js: Unrecognized Content-Security-Policy directive 'prefetch-src'.
js: Uncaught (in promise) #<Object>
js: [DEPRECATED] Please use `subscribeWithSelector` middleware
js: Window state not initialized window-1
js: Window state not …Run Code Online (Sandbox Code Playgroud) qwebengineview ×10
python ×6
pyqt5 ×5
pyqt ×4
c++ ×3
qt ×3
qt5 ×3
javascript ×2
pyside2 ×2
qtwebchannel ×2
chromium ×1
html ×1
pyinstaller ×1
python-3.x ×1
qtwebengine ×1