0

I want to send a http GET request using QWebEngineHttpRequest.

I know it is possible, as I found this question with a POST request using it.

So, I've ended up with some code but it doesn't work. Let's say I want to make a get request to facebook webpage and print the answer, which should be the HTML content of the page.

import sys
from PyQt5 import *
        
def handle_response():
    print(bytes(replyObject.readAll()).decode("utf-8"))
        
if __name__ == "__main__":

    def app():
        app = QApplication(sys.argv)
        req = QtWebEngineCore.QWebEngineHttpRequest(QUrl("https://stackoverflow.com/questions/51686198/", 
            method=QWebEngineHttpRequest.Get)
        req.setHeader(QByteArray(b'Content-Type'),QByteArray(b'application/json'))
        web = QWebEngineView()
        web.loadFinished.connect(on_load_finished) # will be error
        sys.exit(app.exec_())
musicamante
  • 41,230
  • 6
  • 33
  • 58
SonyMag
  • 141
  • 7
  • You got an error because `on_load_finished` does not exist. And you're doing nothing with `req`. Have you read the documentation about [QWebEngineHttpRequest](https://doc.qt.io/qt-5/qwebenginehttprequest.html), specifically where it references the page and view `load()` methods? – musicamante Jan 31 '22 at 22:55

1 Answers1

0

Ok, I found how to make this:

import sys

from PyQt5.QtCore import QByteArray, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineCore import QWebEngineHttpRequest
from PyQt5.QtWebEngineWidgets import QWebEnginePage


class Render(QWebEnginePage):
    def __init__(self, url):
        app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.loadFinished.connect(self._loadFinished)

        self._html = ""

        username = "username"
        password = "password"
        base64string = QByteArray(("%s:%s" % (username, password)).encode()).toBase64()
        request = QWebEngineHttpRequest(QUrl.fromUserInput(url))
        equest.setHeader(b"Authorization", b"Basic: %s" % (base64string,))

        self.load(request)

        app.exec_()

    @property
    def html(self):
        return self._html

    def _loadFinished(self):
        self.toHtml(self.handle_to_html)

    def handle_to_html(self, html):
        self._html = html
        QApplication.quit()


def main():
    url = "http://www.google.com"
    r = Render(url)
    print(r.html)


if __name__ == "__main__":
    main()

Thanks to link

SonyMag
  • 141
  • 7