PyQt5 / PyQt

PyQt Examples(PyQt各种测试和例子) PyQt4 PyQt5
GNU Lesser General Public License v2.1
6.63k stars 1.96k forks source link

Passing cookies to QWebEngineView using python #155

Closed godomainz closed 2 years ago

godomainz commented 2 years ago

so I have a python code which converts url to pdf like below

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

I have a cookie.txt with the content below

  [
    {
        "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"
    }
]

is there a way to pass my cookie.txt to QWebEngineView or QtWebEngineWidgets ??

892768447 commented 2 years ago

https://doc.qt.io/qt-5/qwebenginecookiestore.html

add cookie for url

godomainz commented 2 years ago

@892768447 any sample code on how to do that ?

892768447 commented 2 years ago

https://github.com/PyQt5/PyQt/issues/88

cookieStore.setCookie(cookies.front(), url)

godomainz commented 2 years ago

@892768447 as per your suggestion I changed the code like below

import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkCookie
from PyQt5.QtCore import QUrl, QTimer
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
import argparse

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()
    networkManager = QNetworkAccessManager()
    cookieJar = networkManager.cookieJar()
    cookies = cookieJar.cookiesForUrl(QUrl(url))
    web_profile = loader.page().profile()
    cookieStore = web_profile.cookieStore()
    cookieStore.setCookie(cookies.front(), QUrl(url))
    loader.setUrl(QUrl(url))
    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):
        QTimer.singleShot(2000, lambda: loader.page().printToPdf("test.pdf", pageLayout=layout))

    loader.loadFinished.connect(emit_pdf)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

I'm getting below error

Traceback (most recent call last):
  File ".\htmlToPdfnew.py", line 41, in <module>
    main()
  File ".\htmlToPdfnew.py", line 21, in main
    cookie.path("cookie.txt")
TypeError: path(self): too many arguments
PS F:\Projects\E2E\htmlToPDF> python.exe .\htmlToPdfnew.py --url https://vm2.qa02.oneit.com.au/gds/
Traceback (most recent call last):
  File ".\htmlToPdfnew.py", line 42, in <module>
    main()
  File ".\htmlToPdfnew.py", line 25, in main
    cookieStore.setCookie(cookies.front(), QUrl(url))
AttributeError: 'list' object has no attribute 'front'

btw how can we specify the file path for "cookie.txt" ?

892768447 commented 2 years ago
File ".\htmlToPdfnew.py", line 25, in main
    cookieStore.setCookie(cookies.front(), QUrl(url))
AttributeError: 'list' object has no attribute 'front'

change to  cookies[0]
webEngineProfile = QWebEngineProfile.defaultProfile()
cookieStore = webEngineProfile.cookieStore()

#https://doc.qt.io/qt-5/qwebenginecookiestore.html#setCookie
#cookieStore.setCookie(const QNetworkCookie &cookie, const QUrl &origin = QUrl())

cook = QNetworkCookie()
cook.setDomain('ww.udemy.com')
#cook.setExpirationDate(QDateTime) # date
cook.setPath('/')
cook.setValue('c6sdf99-1sdab-4sd1-86ff-2dc8sfs24511'.encode())
cookieStore.setCookie(cook , QUrl(url))

you can search QNetworkCookie from github like

https://github.com/dean2021/splash/blob/83383a3abf2e2909bdcc5e68a2d58caf2995f605/splash/cookies.py#L82