[Qt-interest] Html parsing
Gordon Schumacher
gordon at rebit.com
Mon Dec 1 18:44:45 CET 2008
Frédéric LECONTE wrote:
> It sounds like a complicated way to do a simple thing...
> No simpliest code ?
>
Don't try and parse the page - that's by far the hard way. Use the
Google API... it hands you XML!
Something like this:
class myClass : public QObject
{
public:
QHttp m_http;
myClass()
{
connect(&m_http, SIGNAL(readyRead(const QHttpResponseHeader &)),
this, SLOT(readResponse(const QHttpResponseHeader &)));
}
void doTranslate(void)
{
QUrl
siteQuery(QLatin1String("http://ajax.googleapis.com/ajax/services/language/translate"));
siteQuery.addQueryItem(QLatin1String("v"), QLatin1String("1.0"));
siteQuery.addQueryItem(QLatin1String("langpair"),
QString::fromUtf8(QUrl::toPercentEncoding(QLatin1String("fr|en")));
#if defined(GOOGLE_KEY) // optional - define GOOGLE_KEY to your
API key
siteQuery.addQueryItem(QLatin1String("key"),
QLatin1String(GOOGLE_KEY));
#endif
header.setValue(QLatin1String("Referrer"),
QLatin1String("http://your-site"));
header.setValue(QLatin1String("Connection"),
QLatin1String("Keep-Alive"));
header.setRequest(QLatin1String("GET"),
siteQuery.toString(QUrl::RemoveScheme | QUrl::RemoveAuthority));
int connId = m_http.request(header);
}
public slots:
void readResponse(const QHttpResponseHeader & resp)
{
QString buildXlateObj = QLatin1String("var xlateObject = ");
QScriptEngine engine;
QString translation;
// Fetch the translation out of the returned JSON object
buildXlateObj += QString::fromUtf8(m_http.readAll()) +
QLatin1String(";");
engine.evaluate(buildXlateObj);
if (!engine.hasUncaughtException())
translation = engine.evaluate(QLatin1String("return
xlateObject.responseData.translatedText;")).toString();
if (!engine.hasUncaughtException())
qDebug() << translation;
}
}
I don't promise this builds and runs, it's taken out of code I have
written elsewhere. But it should get you close!
More information about the Qt-interest-old
mailing list