如何在Webkit窗口中操作页面内容(使用QT和QTWebKit)?

时间:2010-01-09 21:13:21

标签: qt macros webkit

请帮助我理解,如何操作qt webkit窗口中显示的html内容。我需要简单的操作,如填写输入字段和单击按钮。关于此的任何提示/文章?

1 个答案:

答案 0 :(得分:8)

请查看下面的示例。它使用QWebView加载Google页面。然后使用QWebFrame类查找与搜索编辑框和“谷歌搜索”按钮对应的Web元素。使用搜索查询更新编辑框,然后单击搜索按钮。

加载页面:

QWebView::connect(ui->webView, SIGNAL(loadFinished(bool)), this, SLOT(on_pageLoad_finished(bool)));
QUrl url("http://www.google.com/");
ui->webView->load(url);

on_pageLoad_finished实施:

void MainWindow::on_pageLoad_finished(bool ok)
{
    if (ok)
    {
        QWebFrame* frame = ui->webView->page()->currentFrame();
        if (frame!=NULL)
        {
            // set google seatch box
            QWebElementCollection collection = frame->findAllElements("input[name=q]");
            foreach (QWebElement element, collection)
                element.setAttribute("value", "how-to-manipulate-pages-content-inside-webkit-window-using-qt-and-qtwebkit");
            // find search button
            QWebElementCollection collection1 = frame->findAllElements("input[name=btnG]");
            foreach (QWebElement element, collection1)
            {
                QPoint pos(element.geometry().center());
                // send a mouse click event to the web page
                QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
                QApplication::sendEvent(ui->webView->page(), &event0);
                QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
                QApplication::sendEvent(ui->webView->page(), &event1);
            }
        }
    }
}

希望这有帮助,尊重