samedi 25 mars 2023

How to scrape and download images from archillect.com using C++ in QT Framework?

I am trying to build a desktop application which can download image from archillect.com every hour and set it as my Windows wallpaper. But can't understand how to pull images from the site as it has so many pictures in the first page and only if you click one of the pictures, you get the real image link with higher resolution.

Can someone provide me a code snippet for the scrapper part?

#include <QCoreApplication>

#include <QFile>

#include <QNetworkAccessManager>

#include <QNetworkReply>

#include <QScreen>

#include <QStandardPaths>

void setDesktopWallpaper(const QString& imagePath) {

    const wchar_t* wallpaperPath = reinterpret_cast<const wchar_t*>(imagePath.utf16());

    SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, (void*)wallpaperPath, SPIF_UPDATEINIFILE);

}

void downloadImage(const QString& url, const QString& filePath) {

    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly)) {

        qWarning() << "Failed to open file for writing: " << filePath;

        return;

    }

    QNetworkAccessManager manager;

    QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(url)));

    QCoreApplication::processEvents();

    while (!reply->isFinished()) {

        QCoreApplication::processEvents();

    }

    if (reply->error() != QNetworkReply::NoError) {

        qWarning() << "Failed to download image: " << reply->errorString();

        return;

    }

    const QByteArray data = reply->readAll();

    file.write(data);

    file.close();

    setDesktopWallpaper(filePath);

}

void changeWallpaperFromUrl(const QString& url) {

    const QString filePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + "/wallpaper.jpg";

    downloadImage(url, filePath);

}

int main(int argc, char *argv[]) {

    QCoreApplication app(argc, argv);

    const QString url = "https://archillect.com/";

    changeWallpaperFromUrl(

URL);

    return app.exec();

}

Aucun commentaire:

Enregistrer un commentaire