开发者

Render HTML on headless server to produce screenshots

开发者 https://www.devze.com 2023-01-29 07:58 出处:网络
I would like to create screenshots of web pages from a given URL.开发者_如何转开发 While it\'s possible to use tools like Selenium RC, that requires a graphical environment. I am running a headless Ge

I would like to create screenshots of web pages from a given URL.开发者_如何转开发 While it's possible to use tools like Selenium RC, that requires a graphical environment. I am running a headless Gentoo server.

This will be part of a tool chain that works like:

  • Fetch URL
  • Render HTML
  • Export render as image file
  • Store image file


You can run an application with framebuffer X-Server like xvfb - one simple approach is a Qt based app to render the page in a webkit widget and save as an image. Here's a blog post outlining how this can be done with Python.

Here's a quick command line tool I've used with Qt. It's a while since I used it but it should still work!

#include <QtCore/QCoreApplication>
#include <QtGui>
#include <QtWebKit>
#include <QTextStream>
#include <QSize>

QWebView *view;
QString outfile;

void QWebView::loadFinished(bool ok)
{
        QTextStream out(stdout);
        if (!ok) {
                out << "Page loading failed\n";
                return;
        }
        view->page()->setViewportSize(view->page()->currentFrame()->contentsSize());
        QImage *img = new QImage(view->page()->viewportSize(), QImage::Format_ARGB32);
        QPainter *paint = new QPainter(img);
        view->page()->currentFrame()->render(paint);
        paint->end();
        if(!img->save(outfile, "png"))
                out << "Save failure\n";
        QApplication::quit();
        return;
}

int main(int argc, char *argv[])
{
        QTextStream out(stdout);
        if(argc < 3) {
                out << "USAGE: " << argv[0] << " <url> <outfile>\n";
                return -1;
        }
        outfile = argv[2];
        QApplication app(argc, argv);
        view = new QWebView();
        view->load(QUrl(argv[1]));

        return app.exec();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消