6

我想获取网页的源代码(HTML),例如 StackOverflow 的主页。

这是我到目前为止编码的内容:

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

QString html = response->readAll(); // Source should be stored here

但是什么也没有发生!当我尝试获取html字符串的值时,它是空的(“”)。

那么该怎么办?我正在使用 Qt 5.3.1。

4

3 回答 3

8

您需要以异步方式对其进行编码。C++11 和 Qt 来救援。请记住,lambda 的主体稍后将在事件循环中执行。

// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>

void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) {
   QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
   QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url)));
   QObject::connect(response, &QNetworkReply::finished, [response, fun]{
      response->deleteLater();
      response->manager()->deleteLater();
      if (response->error() != QNetworkReply::NoError) return;
      auto const contentType =
            response->header(QNetworkRequest::ContentTypeHeader).toString();
      static QRegularExpression re("charset=([!-~]+)");
      auto const match = re.match(contentType);
      if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) {
         qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType;
         return;
      }
      auto const html = QString::fromUtf8(response->readAll());
      fun(html); // do something with the data
   }) && manager.take();
}

int main(int argc, char *argv[])
{
   QCoreApplication app(argc, argv);
   htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); });
   return app.exec();
}

除非您只使用此代码一次,否则您应该将QNetworkManager实例作为控制器类的成员,或放在main等中。

于 2014-07-26T00:24:58.433 回答
6

QNetworkAccessManager异步工作。您readAll()在 之后立即致电get(),但当时尚未提出请求。您需要使用文档QNetworkAccessManager::finished中显示的信号并移动到连接到此信号的插槽。readAll()

于 2014-07-25T23:52:29.017 回答
6

您必须在之间添加 QEventLoop。

QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response,SIGNAL(finished()),&event,SLOT(quit()));
event.exec();
QString html = response->readAll(); // Source should be stored here
于 2014-07-25T23:52:52.400 回答