Set QWebView to mobile dimensions

380 views Asked by At

I am trying to crawl certain pages on this site as a mobile user. I set the user agent to match an iPhone, and am trying to set the dimensions to match 320x568. After that, I want to take a screenshot so I can see what all the pages look like, and make sure everything is correct. However, it's always the desktop view. How can I set QWebView or QWebPage to the mobile dimensions when I load a specific page?

Below self.qweb is a QWebView. I saw this question using QMainWindow, but this is a headless crawl, and it works great as is, except for setting the width & height of the "browser" view. I tried variations of it, waiting for the page to load, and then resetting the size, but it's not working.

if hasattr(self, 'height') and hasattr(self, 'width'):
    size = self.qweb.page().mainFrame().contentsSize()
    self.qweb.resize(320, 568)

self.qweb.setPage(self.Page())
self.qweb.loadFinished.connect(self.loaded_page)

UPDATE I just tried this as well, but after the page is loaded, the QSize returned is 980x568. I even tried the same function calls in the loaded_page method after the page loads, but that didn't work either. It just resets the view to a much larger size when another action on the page is performed.

    self.qweb.setPage(self.Page())
    self.qweb.page().setViewportSize(QtCore.QSize(320, 568))
    self.qweb.page().setPreferredContentsSize(QtCore.QSize(320, 568))
    self.qweb.loadFinished.connect(self.loaded_page)

def loaded_page(self):
    # this returns QSize(980,568)
    size = self.qweb.page().mainFrame().contentsSize()

This is my Page setup

class Page(QWebPage):
    """QWebPage implementation with a custom user agent string"""

    def __init__(self):
        QWebPage.__init__(self)

        # Settings
        s = self.settings()
        s.setAttribute(QWebSettings.AutoLoadImages, True)
        s.setAttribute(QWebSettings.JavascriptCanOpenWindows, True)
        s.setAttribute(QWebSettings.PluginsEnabled, True)
1

There are 1 answers

0
ekhumoro On BEST ANSWER

It sounds like you need to set the preferred contents size:

    page.setPreferredContentsSize(QtCore.QSize(320, 568))

But if that doesn't give the right results, try setting the viewport size:

    page.setViewportSize(QtCore.QSize(320, 568))