问题
I posted the question below, trying to use the QDomDocument classes. I was advised to use the QWebkit instead, but I'm very confused how to do what I need to do with QWebkit. I've never used it before so I'm rather unsure with it. Could anyone please offer any advice? Thanks! For the record, the function is using a QByteArray that when translated to text is a standard HTML file.
ORIGINAL QUESTION:
I have several divs in an HTML file with different classes, like this:
<div class='A'>...</div>
<div class='B'>...</div>
<div class='C'>...</div>
I have a Qt (4.7) program where I need to be able to get a certain div out of this based on the class. I need to use QDomDocument in this program. I know from the documentation that that class has a function elementById()
, but I can't get that to work with classes, just ids. This isn't a HTML file a made or anything, so I don't have any control over whether it's class or id. Is there a way to do this that I'm missing? Thanks!
回答1:
.pro
QT += webkitwidgets
main.cpp
#include <QApplication>
#include <QDebug>
#include <QWebView>
#include <QWebFrame>
#include <QWebElement>
int main( int argc, char *argv[] ) {
QApplication a(argc, argv);
QString l_html( "<html><body>"
"<div class='A'>div with class A</div>"
"<div class='B'>div with class B</div>"
"<div class='C'>div with class C</div>"
"<span class='A'>span with class A</span>"
"</body></html>" );
QWebView l_webView; // you can skip the QWebView if you dont want to show any widget
l_webView.page()->mainFrame()->setHtml( l_html );
QWebElement l_root( l_webView.page()->mainFrame()->documentElement() );
QWebElementCollection l_elements( l_root.findAll( ".a" ) );
foreach ( QWebElement l_e, l_elements ) {
// do what you want here
}
return a.exec();
}
来源:https://stackoverflow.com/questions/20690202/using-qwebkit-to-retrieve-divs-with-a-specific-class