Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature request: give the ability to accept cookie file directly from QWebEngineView #157

Closed
godomainz opened this issue May 12, 2022 · 3 comments
Labels

Comments

@godomainz
Copy link

godomainz commented May 12, 2022

proposing setCookie method to QWebEngineView
example :

loader = QtWebEngineWidgets.QWebEngineView()
loader.setCookie("/path/to/cookie.txt")

setCookie should read the file and use that when loading the url
sample cookie.txt can be created using chrome Cookie-Editor plugin

@892768447
Copy link
Member

There is no direct official interface
https://doc.qt.io/qt-5/qwebengineview-members.html

We can do it ourselves.
I will provide a demo later.

@892768447
Copy link
Member

@godomainz
Copy link
Author

Thanks @892768447 it works

if anyone wonders this is how I did it

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()

@892768447 892768447 added 求助 fixed 已修复 and removed fixed 已修复 labels Feb 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants