how to write all the

tags to text file

2019-03-06 09:44发布

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条回答
forever°为你锁心
2楼-- · 2019-03-06 10:26

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;
}
查看更多
登录 后发表回答