【问题标题】:extract information from a website using Qt?使用 Qt 从网站中提取信息?
【发布时间】:2013-09-12 08:19:38
【问题描述】:

我想在b 标签中提取information => 123456789

这是 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 应该会自动设置文本123456789。但是我的代码不起作用。 LineEdit 的文本保持为空。

我包括这个:

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

QT file.pro 是:

QT += core gui
QT += network
QT += webkit
QT += webkitwidgets

【问题讨论】:

  • 考虑在点击“更新”按钮之前给 webview 时间来加载页面完成
  • 不,你没有。至少这是您的代码所说的。您在 on_pushButton_clicked 插槽中加载您的网站。在同一个插槽中,您尝试评估结果。立即下载?使用 QWebView 的 loadFinished 信号来确定您的 url 加载何时完成。 那么您可以尝试评估内容。
  • 还有,我如何使用 loadFinished() ?你能举个例子吗

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


【解决方案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() 方法中,您只加载页面(如果需要,则显示 web 视图)

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());
    }

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多