how to write all the <p> tags to text file

瘦欲@ 提交于 2019-12-20 06:08:31

问题


I need to write Qt/C++ code to extract all the p tags to write each p tag to .txt file, For example if I have the following HTML page:

        <!DOCTYPE html>
        <html>
         <body>

         <h1>My First Heading</h1>

         <p>My first paragraph.</p>
         <p>My second paragraph.</p>

         </body>
          </html>

I need the code to create 2 .txt file the first one will include My first paragraph. and the second will include My second paragraph.

my problem how to parse the html and get the txt between the tags, here my code

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

           QEventLoop loop;

            QNetworkRequest request;
             request.setUrl(QUrl("http://en.wikipedia.org/wiki/Cars"));
               QNetworkAccessManager* networkMgr = new QNetworkAccessManager();
                QNetworkReply* reply = networkMgr->get(request);

             QObject::connect(reply, SIGNAL(finished()),&loop,SLOT(quit()));

                        loop.exec();

                 QFile file ("/Users/David/Desktop/text123.txt");
                   file.open(QIODevice::WriteOnly);
                   file.write(reply->readAll());

                         delete reply;

                   return a.exec();
                     }

Thank you so much for your help

  1. List item

回答1:


you can use QRegularExpression for this see example below.

QString txt = reply->readAll();
QRegularExpression regex("< *[pP] *>(.*)< *\\/ *[pP] *>");
QRegularExpressionMatchIterator it = regex.globalMatch(txt);
int i = 0;
while(it.hasNext())
{
    QRegularExpressionMatch match = it.next();
    QString filename = QString("e:/folder/file%1.txt").arg(i);
    QFile file (filename);
    file.open(QIODevice::WriteOnly);
    file.write(match.captured(1).toUtf8());
    file.close();
    ++i;
}


来源:https://stackoverflow.com/questions/17632550/how-to-write-all-the-p-tags-to-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!