使用Qt从网站中提取信息?

时间:2013-09-08 20:07:49

标签: c++ html qt html-content-extraction

我想提取information tag =>中的b123456789

这是HTML源代码:

<body>
       <div>
          <table>
               <tbody>
                     <tr>
                         <td class="myclass">
                               <b>123456789</b>
                         </td>
                     </tr>
              </tbody>
          </table>
       </div>
 </body>

所以,我试过这个:

void My_Test_Dialog::on_pushButton_clicked()
{


        QWebView *webview = new QWebView(parentWidget());

        webview->load(QUrl("http://www.esesese.com"));

        webview->show();

         // get HTML element information
        QWebElementCollection colls = webview->page()->mainFrame()->findAllElements("td.myclass b");



         foreach(QWebElement elemento, colls)
        {
                    ui->lineEdit_data->setText(elemento.toInnerXml());
        }
}

我有一个带有按钮(call update)和LineEdit的表单,因此,如果我点击update按钮,LineEdit应设置文字{{ 1}}自动。但我的代码不起作用。 123456789的文字仍为空。

我包括这个:

LineEdit

QT file.pro是:

#include <QtWebKit>
#include <QtWebKitWidgets/QWebFrame>
#include <QWebView>

1 个答案:

答案 0 :(得分:1)

如前所述,您需要确保等待足够长的时间才能加载QWebView中的数据。

你可以这样做(非常简单):

将webView定义为对话框类的一部分,并声明一个可以在以后连接到Web视图信号的插槽

class My_Test_Dialog
{
public slots:

  // slot to read your data once you are finished
  void readPage(bool ok);

  // whatever else you did
private: 
  QWebView *webView;

}

然后,例如在构造函数或其他地方,您可以创建webView并将其loadFinished()信号连接到上面类定义中显示的readPage()插槽

// create QWebview and connect its loadFinished signal to our slot 
webView = new QWebView(this);
QObject::connect(webView,SIGNAL(loadFinished(bool)), this, SLOT( readPage(bool) ) );

然后在您的on_pushButton_clicked()方法中,您只加载页面(如果您需要,则显示网页视图)

void My_Test_Dialog::on_pushButton_clicked()
{
  webView->load(QUrl("http://www.esesese.com"));
}

然后一旦对话框完成加载,将自动调用插槽readData(),您只需执行读操作

void MyDialog::readPage(bool ok)
{
  // get HTML element information                                                                                                                                                                    
  QWebElementCollection colls = webView->page()->mainFrame()->findAllElements("td.myclass b");

  foreach(QWebElement elemento, colls)
    {
      lineEdit->setText(elemento.toInnerXml());
    }

}

如果这有帮助,请告诉我。

相关问题