1 Qter豆
本帖最后由 Qt1442 于 2018-1-6 22:23 编辑
void Widget :: on_pushButton_clicked(){
QString Film_Name="芳华 " ;
QString Douban="豆瓣电影" ;
Write_Html(Film_Name+Douban);
}
int Widget ::Write_Html( const QString Douban_FN)
{
QByteArray Decode_Baidu = (Douban_FN.toUtf8()).toPercentEncoding(); //中文字符转码解码
QString Result_Url= "https://www.baidu.com/s?wd=" +Decode_Baidu+ "&ie=UTF-8" ; //拼合链接
QUrl url(Result_Url);
ui -> label ->setText(Result_Url);
QDesktopServices :: openUrl(Result_Url);
QNetworkAccessManager manager;
QEventLoop loop;
QTextCodec *codec;
QNetworkReply *reply;
QString codeContent;
const QString File_Name = "Baidu_Code.html" ;
qDebug () << "Reading html code form " << Result_Url;
reply = manager.get( QNetworkRequest (url)); //请求结束并下载完成后,退出子事件循环
QObject ::connect(reply, SIGNAL (finished()), &loop, SLOT (quit())); //开启子事件循环
loop.exec(); //获取源码,打开文件
QFile Http_File(File_Name);
if ( !Http_File. open ( QIODevice :: WriteOnly | QIODevice :: Text ) ) { qDebug () << "Cannot open the file: " << File_Name; return 0 ; }
QTextStream out(&Http_File);
codeContent = reply->readAll(); //将获取到的网页源码写入文件。一定要注意编码问题,否则很容易出现乱码的
codec = QTextCodec ::codecForHtml(codeContent.toUtf8());
codeContent = codec->toUnicode(codeContent.toUtf8());
out.setCodec(codec);
out << codeContent << endl;
Http_File.close ();
qDebug () << "Finished, the code have written to " << File_Name;
return 0 ;
}
编译输出如下:Starting F:\Qt\build-href-Desktop_Qt_5_8_0_MinGW_32bit-Debug\debug\href.exe...
Reading html code form "https://www.baidu.com/s?wd=%E8%8A%B3%E5%8D%8E%20%E8%B1%86%E7%93%A3%E7%94%B5%E5%BD%B1&ie=UTF-8"
Finished, the code have written to "Baidu_Code.html"
F:\Qt\build-href-Desktop_Qt_5_8_0_MinGW_32bit-Debug\debug\href.exe exited with code 0
获取到的内容为:<html><head> <script> location.replace(location.href.replace("https://","http://")); </script></head><body> <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript></body></html>然而用浏览器在链接前增加view-source:、或者通过浏览器的网页另存为功能保存网页并打开,显示的内容很多很多,也才是我真正想获取的源码。求解应该怎么办
我来回答