zoukankan      html  css  js  c++  java
  • QT:轻松获取网页源码

    获取网页源码的小例子,代码很简单,就不多作解释了。

    不过一定要注意网页的编码问题,否则会出现乱码的!!!

    1. #include <QtCore>      
    2. #include <QtNetwork>      
    3.     
    4. //网页地址      
    5. const QString URLSTR = "http://www.csdn.net/";      
    6. //储存网页代码的文件      
    7. const QString FILE_NAME = "code.html";      
    8.     
    9. int main(int argc, char **argv)      
    10. {      
    11.     QCoreApplication app(argc, argv);      
    12.     QUrl url(URLSTR);      
    13.     QNetworkAccessManager manager;      
    14.     QEventLoop loop;      
    15.     QTextCodec *codec;    
    16.     QNetworkReply *reply;    
    17.     
    18.     qDebug() << "Reading html code form " << URLSTR;      
    19.     reply = manager.get(QNetworkRequest(url));      
    20.     //请求结束并下载完成后,退出子事件循环      
    21.     QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));      
    22.     //开启子事件循环      
    23.     loop.exec();      
    24.     
    25.     //获取源码,打开文件  
    26.     QFile file(FILE_NAME);    
    27.     if( !file.open(QIODevice::WriteOnly | QIODevice::Text) )  
    28.     {  
    29.         qDebug() << "Cannot open the file: " << FILE_NAME;  
    30.         return 0;  
    31.     }  
    32.     QTextStream out(&file);    
    33.     QString codeContent = reply->readAll();    
    34.   
    35.     //将获取到的网页源码写入文件  
    36.     //一定要注意编码问题,否则很容易出现乱码的  
    37.     codec = QTextCodec::codecForHtml(codeContent.toAscii());    
    38.     codeContent = codec->toUnicode(codeContent.toAscii());    
    39.     out.setCodec(codec);  
    40.     out << codeContent << endl;    
    41.     file.close();    
    42.     qDebug() << "Finished, the code have written to " << FILE_NAME;      
    43.     return 0;      
    44. }      

    http://blog.csdn.net/small_qch/article/details/7200271

  • 相关阅读:
    [记录]Eclipse版本选择和安装
    Nexus+Maven安装配置手册
    Eclipse编写Java程序
    Tomcat下载和配置
    SQL Server如何清除连接过的服务器名称历史?
    为文本添加全选Ctrl + A 功能
    配置Eclipse使用TFS源码管理
    [jQuery] jSrcollable
    [ios] cocos2d/cocos2dx 演示
    [c++] 实现类似printf这样的函数
  • 原文地址:https://www.cnblogs.com/findumars/p/4993551.html
Copyright © 2011-2022 走看看