所以我有一个 python 代码,可以将 url 转换为 pdf,如下所示
import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl, QTimer
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
import argparse
def _fullScreenRequested(request):
request.accept()
loader.showFullScreen()
def main():
url = ''
parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--url", help="Type url")
args = parser.parse_args()
config = vars(args)
url = config['url']
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
layout = QPageLayout()
layout.setPageSize(QPageSize(QPageSize.A4Extra))
layout.setOrientation(QPageLayout.Portrait)
loader.load(QUrl(url))
loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())
def emit_pdf(finished):
# loader.page().printToPdf("test.pdf", pageLayout=layout)
QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf", pageLayout=layout))
loader.loadFinished.connect(emit_pdf)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
我有一个 cookie.txt,内容如下
[
{
"domain": "www.udemy.com",
"expirationDate": 1714906174.734258,
"hostOnly": true,
"httpOnly": false,
"name": "snexid",
"path": "/",
"sameSite": null,
"secure": false,
"session": false,
"storeId": null,
"value": "c6sdf99-1sdab-4sd1-86ff-2dc8sfs24511"
}
]
有没有办法将 cookie.txt 传递给
QWebEngineView
或 QtWebEngineWidgets
??
好吧,所有建议都没有被唤醒。
但是这个例子有效 --> https://github.com/PyQt5/PyQt/blob/master/QWebEngineView/SetCookies.py
这是我的完整代码
import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl, QTimer, QDateTime, Qt
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
from PyQt5.QtNetwork import QNetworkCookie
import argparse
import os
import json
cookie_file = None
class Window(QtWebEngineWidgets.QWebEngineView):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.cookieStore = self.page().profile().cookieStore()
def initCookies(self, cookie_file):
if cookie_file:
with open("output/"+cookie_file, encoding='utf8') as f:
cookies = json.load(f)
for cookie in cookies:
qcookie = QNetworkCookie()
qcookie.setName(cookie.get('name', '').encode())
qcookie.setValue(cookie.get('value', '').encode())
qcookie.setDomain(cookie.get('domain', ''))
qcookie.setPath(cookie.get('path', ''))
qcookie.setExpirationDate(
QDateTime.fromString(str(cookie.get('expirationDate', 0)),
Qt.ISODate))
qcookie.setHttpOnly(cookie.get('httpOnly', False))
qcookie.setSecure(cookie.get('secure', False))
self.cookieStore.setCookie(qcookie, QUrl())
def main():
file_name = 'ABC123.pdf'
parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--url", help="Type url", required=True)
parser.add_argument("--output", help="Type output pdf file name")
parser.add_argument("--cookie", help="Type cookie file name")
args = parser.parse_args()
config = vars(args)
url = config['url']
output = config['output']
cookie = config['cookie']
if output:
file_name = output
if cookie:
cookie_file = cookie
app = QtWidgets.QApplication(sys.argv)
loader = Window()
loader.initCookies(cookie_file)
loader.setZoomFactor(1)
layout = QPageLayout()
layout.setPageSize(QPageSize(QPageSize.A4Extra))
layout.setOrientation(QPageLayout.Portrait)
loader.load(QUrl(url))
loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())
def emit_pdf(finished):
directory = "/htmltopdf/output/"
if not os.path.exists(directory):
os.makedirs(directory)
QTimer.singleShot(2000, lambda: loader.page().printToPdf(directory+file_name, pageLayout=layout))
loader.loadFinished.connect(emit_pdf)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
更新了 PyQT6:
from PyQt6.QtCore import QUrl, QSize, QDateTime, Qt, QUrl
from PyQt6.QtGui import QKeySequence, QAction
from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QToolBar
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import QWebEngineProfile, QWebEnginePage
from PyQt6.QtNetwork import QNetworkCookie
import json
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
QMainWindow.__init__(self, *args, **kwargs)
# super().__init__()
self.setMinimumWidth(1024)
self.setMinimumHeight(800)
# Create a web view
self.webview = QWebEngineView()
profile = QWebEngineProfile("storage", self.webview)
cookie_store = profile.cookieStore()
cookie_store.cookieAdded.connect(self.onCookieAdded)
self.cookies = []
webpage = QWebEnginePage(profile, self.webview)
self.webview.setPage(webpage)
self.webview.load(QUrl("https://stackoverflow.com/questions/48150321/obtain-cookies-as-dictionary-from-a-qwebengineprofile"))
self.setCentralWidget(self.webview)
# Create a toolbar
toolbar = QToolBar()
self.addToolBar(toolbar)
# Add a back action to the toolbar
back_action = QAction("Back", self)
back_action.setShortcut(QKeySequence("Back"))
back_action.triggered.connect(self.webview.back)
toolbar.addAction(back_action)
# Add a forward action to the toolbar
forward_action = QAction("Forward", self)
forward_action.setShortcut(QKeySequence("Forward"))
forward_action.triggered.connect(self.webview.forward)
toolbar.addAction(forward_action)
# Add a reload action to the toolbar
reload_action = QAction("Reload", self)
reload_action.setShortcut(QKeySequence("Refresh"))
reload_action.triggered.connect(self.webview.reload)
toolbar.addAction(reload_action)
# Add a search bar to the toolbar
self.search_bar = QLineEdit()
self.search_bar.returnPressed.connect(self.load_url)
toolbar.addWidget(self.search_bar)
def onCookieAdded(self, cookie):
for cookie in self.cookies:
if cookie.hasSameIdentifier(cookie):
return
self.cookies.append(QNetworkCookie(cookie))
self.toJson()
def toJson(self):
cookies_list_info = []
for c in self.cookies:
data = {
"name": bytearray(c.name()).decode(),
"domain": c.domain(),
"value": bytearray(c.value()).decode(),
"path": c.path(),
"expirationDate": c.expirationDate().toString(),
"secure": c.isSecure(),
"httponly": c.isHttpOnly()
}
cookies_list_info.append(data)
print("Cookie as list of dictionary:")
print(cookies_list_info)
def load_url(self):
url = self.search_bar.text()
if not url.startswith("http"):
url = "https://" + url
self.webview.load(QUrl(url))
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
仅此行:
"expirationDate": c.expirationDate().toString(),
我不确定这是否正确 - 它有效,但尝试如下:
"expirationDate": c.expirationDate().toString(QDateTime),
最终会出现运行时错误。
提供的代码对我非常有帮助,小部件现在可以正常工作,可以通过会话/重新启动小部件来保存凭据。