StationScheduleItem parseResult(const QWebElement &result) { StationScheduleItem item; QWebElement current = result.findFirst("h2"); if (!current.isNull()) { item.setTrain(current.toPlainText()); } parseDetailsUrl(result, item); current = result.findFirst("div.bloccotreno"); parseDelayClass(current, item); QString rawText = current.toPlainText(); parseTrain(rawText, item); qDebug() << "train:" << item.train(); qDebug() << "delayClass:" << item.delayClass(); qDebug() << "detailsUrl:" << item.detailsUrl(); qDebug() << "departureStation:" << item.departureStation(); qDebug() << "departureTime:" << item.departureTime(); qDebug() << "arrivalStation:" << item.arrivalStation(); qDebug() << "arrivalTime:" << item.arrivalTime(); qDebug() << "expectedPlatform:" << item.expectedPlatform(); qDebug() << "actualPlatform:" << item.actualPlatform(); qDebug() << "delay:" << item.delay(); return item; }
/* Fonction pour recuperer les données de la requete HTTP Pour chaque couple de devises, on crée un objet 'CoupleDevise' et on y stocke les valeurs récupéré du web service. On accède aux valeurs par le biais des CSSselector grace à un QWebElement */ void Principal::recupereDonnees() { QWebElement element ; // On parse 'urlChoixDevises' pour savoir sur quel couple de devises il faut boucler QStringList listeCouples ; listeCouples = urlChoixDevises.split(";"); listeCouples.removeLast(); listeCouples.replaceInStrings(" ", ""); // Boucle pour recuperer les valeurs pour chaque couple de devises foreach (QString index, listeCouples) { CoupleDevise couple ; element = webView->page()->mainFrame()->findFirstElement("tr#pair_" + index + " span.ftqa11bb") ; // CSSselector pour le nom du couple de devises couple.coupleDevise = element.toPlainText() ; element = webView->page()->mainFrame()->findFirstElement("tr#pair_" + index + ">td[class*=bid]") ; // CSSselector pour la valeur d'achat couple.valeurAchat = element.toPlainText() ; element = webView->page()->mainFrame()->findFirstElement("tr#pair_" + index + ">td[class*=ask]") ; // CSSselector pour la valeur de vente couple.valeurVente = element.toPlainText() ; element = webView->page()->mainFrame()->findFirstElement("tr#pair_" + index + ">td[class*=pcp]") ; // CSSselector pour le pourcentage de variation de la cotation couple.variation = element.toPlainText() ; // Puis on demande a l'objet 'CoupleDevise' de se sauvegarder dans la bdd couple.save(&db) ; }
void MainWindow::showCurrentQuote() { QWebElement rating = webpage->page()->mainFrame()->findFirstElement("span[class=rating]"); QWebElement text = webpage->page()->mainFrame()->findFirstElement("div[class=text]"); currentRating->setText(QString(rating.toPlainText())); currentQuote->setText(QString(text.toPlainText())); NumberOfCurrentQuote->setText(QString::number(currentID)); disableButtons(false); }
void MainWindow::showFirstQuote() { QWebElement firstQuoteID = webpage->page()->mainFrame()->findFirstElement("a[class=id]"); maxID = (firstQuoteID.toPlainText().mid(1)).toInt(); currentID = maxID; showCurrentQuote(); }
QString DumpRenderTreeSupportQt::plainText(const QVariantMap& range) { QVariant v = range.value(QLatin1String("startContainer")); ASSERT(v.isValid()); QWebElement startContainer = qvariant_cast<QWebElement>(v); return startContainer.toPlainText(); }
void GoogleChat::loginPage(bool ok) { QString location = form.webView->url().toString(); if (!ok) { if (location.indexOf("CheckCookie")) return; showError("Service unavailable"); } else { // check for any error message QWebElement e = document().findFirst(".errormsg"); if (e.isNull()) { form.stackedWidget->setCurrentIndex(2); QTimer::singleShot(500, this, SLOT(hideElements())); return; } QString err = "Unknown login failure."; const QString errorMessage = e.toPlainText(); if (!errorMessage.isEmpty()) { err = errorMessage; err = err.simplified(); } showError(err); } }
//void ArestShopPlugin::SinglePageFound() //{ //#ifdef USE_WEBKIT // QWebFrame * ptrFrame = getWebPage()->mainFrame(); // parseProductPage(m_stCompData); // m_stCompData.strCompURL = ptrFrame->url().toString(); // emit priceSearchedFinished(m_stCompData); // productFoundFinish(); //#endif //}; void ArestShopPlugin::parseSearchProductPage(SearchResult & stResult,bool & bNextPage) { //run XML search page parse bNextPage=false; #ifdef USE_WEBKIT QWebFrame * ptrFrame = getWebPage()->mainFrame(); ////////////////////////////////////////////////////////////////////////// QWebElementCollection tableProdRows = ptrFrame->findAllElements("table[class=pricelist]"); for(int iIndex=0;iIndex<tableProdRows.count();++iIndex) { QWebElement prodNameHeader = tableProdRows.at(iIndex).findFirst("td[class=nazwa]"); if (prodNameHeader.isNull()) continue; QWebElement productLink = prodNameHeader.findFirst("a"); QUrl stProductURL = productLink.attribute("href"); ////////////////////////////////////////////////////////////////////////// QString strName = productLink.toPlainText(); stResult.insert(std::make_pair(strName,stProductURL)); } ////////////////////////////////////////////////////////////////////////// QWebElement tablePageNavi = ptrFrame->findFirstElement("li[class=next]"); if (tablePageNavi.isNull()) { bNextPage=false; return; } bNextPage=true; #endif stResult.insert(Arest::mSearchResult.begin(),Arest::mSearchResult.end()); bNextPage=m_bLoadNextPage; }
void MainWindow::updateDonationMeter() { QWebElement e = ui->webView->page()->mainFrame()->findFirstElement("span#ds_bar_67_percentText"); QString value = e.toPlainText(); QString num = value.mid(0, value.indexOf("%")); ui->donationBar->setValue(num.toInt()); ui->label_current_work->setText("Donation meter loaded."); }
void BashRSS::readBash() { nextButton->setEnabled(false); enableDisableButtons(false); QWebElement bashText = commonWidget.findFirst("div[class=text]"); QWebElement ratingValue = commonWidget.findFirst("span[class=rating]"); QWebElement idValue = commonWidget.findFirst("a[class=id]"); bashTextEdit->clear(); bashTextEdit->textCursor().insertText(bashText.toPlainText()); ratingLineEdit->clear(); ratingLineEdit->setText(ratingValue.toPlainText()); idLineEdit->clear(); idLineEdit->setText(idValue.toPlainText()); if (ratingLineEdit->text() == "") { enableDisableButtons(false); } else enableDisableButtons(true); nextButton->setEnabled(true); }
QString message_view::body_as_text() { #if QT_VERSION<0x040600 QVariant res = m_bodyv->page()->mainFrame()->evaluateJavaScript("document.getElementsById('manitou-body').innerHTML"); return res.toString(); #else QWebElement elt = m_bodyv->page()->mainFrame()->findFirstElement("div#manitou-body"); if (!elt.isNull()) { return elt.toPlainText(); } else return ""; #endif }
FightBox MWBotWin::getGroupResult() { FightBox res; QWebElement elm; QString str; elm = frm->findFirstElement("form#fightGroupForm h3 div.group2"); str = elm.toPlainText(); res.enemy.name = str.split("(").first().trimmed(); res.enemy.type = elm.findFirst("i").attribute("class"); res.enemy.level = -1; res.result = str.contains("(0/") ? 1 : 0; res.items = getGroupResultMain(); elm = frm->findFirstElement("td.log div.result div.button div.c"); if (!elm.isNull()) { clickElement(elm); } res.items.append(getDuelResultExtra()); return res; }
void LyricsManiaAPI::onGetLyricPageResult() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(QObject::sender()); bool found = false; Lyric* lyric = 0; if (reply->error() != QNetworkReply::NoError) { qCritical() << "Cannot fetch lyric"; } else { QWebPage page; page.settings()->setAttribute(QWebSettings::AutoLoadImages, false); page.settings()->setAttribute(QWebSettings::JavascriptEnabled, false); page.mainFrame()->setHtml(reply->readAll()); QWebElement lyricbox = page.mainFrame()->findFirstElement("div[class=lyrics-body]"); if (lyricbox.isNull()) { qCritical() << "Cannot find lyric text in HTML page"; } else { // Remove the video div lyricbox.findFirst(QStringLiteral("div")).removeFromDocument(); // Remove the song title lyricbox.findFirst(QStringLiteral("strong")).removeFromDocument(); lyric = lyrics.take(reply); if (!lyric) { qCritical() << "Got an invalid lyric object!"; } else { lyric->setText(lyricbox.toPlainText()); found = true; } } } qDebug() << "Lyric found:" << found; Q_EMIT lyricFetched(lyric, found); reply->deleteLater(); }
void MWBotWin::checkPolice() { QWebElement elm = frm->findFirstElement("a.bubble span.text"); if (elm.toPlainText().contains(trUtf8("Задержан за бои"))) { loadPath(QStringList() << "square" << "police"); getFastRes(); if (!opt.police.fine || (info.ore < 5)) { if (state.botWork) start(); log(trUtf8("Вы задержаны. Бот остановлен")); } else { clickElement("form#fine-form div.button div.c"); log(trUtf8("Заплачен штраф в полиции")); } if (opt.police.relations && (info.ore > 20)) { elm = frm->findFirstElement("form.police-relations div.button div.c"); if (!elm.isNull()) { clickElement("form.police-relations div.button div.c"); log(trUtf8("Связи в полиции продлены")); } } } }
void ArestShopPlugin::parseProductPage() { #ifdef USE_WEBKIT QWebFrame * ptrFrame = getWebPage()->mainFrame(); printPageContent(ptrFrame->toHtml()); QWebElement elCompFullName = ptrFrame->findFirstElement("h1[class=nazwatowaru]"); QWebElement elPrice = ptrFrame->findFirstElement("span[class=price]"); //div class="altFontFace price" QString strPrice = elPrice.toPlainText(); for(int i = 0;i<strPrice.size();i++) { if (strPrice.at(i).isLetterOrNumber()) continue; strPrice = strPrice.left(i); break; } m_stCompData.dPrice = strPrice.toDouble(); m_stCompData.eSearchResult = SR_COMPFOUND; m_stCompData.strCompURL = getWebPage()->mainFrame()->url().toString(); #endif #ifdef USE_XML_PARSER m_stCompData.dPrice = Arest::dPrice; m_stCompData.eSearchResult = SR_COMPFOUND; #endif }
void StationScheduleModel::parse(const QByteArray &htmlReply, const QUrl &baseUrl) { Q_UNUSED(baseUrl); qDebug() << "--- start of query result --- cut here ------"; qDebug() << QString::fromUtf8(htmlReply.constData()); qDebug() << "--- end of query result ----- cut here ------"; emit layoutAboutToBeChanged(); beginResetModel(); QWebPage page; page.mainFrame()->setContent(htmlReply, "text/html", baseUrl); QWebElement doc = page.mainFrame()->documentElement(); // Check if the page is reporting an error before parsing it QWebElement errorElement = doc.findFirst("span.errore"); if (!errorElement.isNull()) { m_departureSchedules.clear(); m_arrivalSchedules.clear(); QString errorText = errorElement.toPlainText().trimmed(); if (errorText == "localita' non trovata") { setError(tr("Unknown station")); } else { setError(tr("Unknown error")); } qDebug() << "error:" << error(); return; } // Find the first div QWebElement current = doc.findFirst("div"); qDebug() << "skipping to the departures"; // Skip to the first div of class corpocentrale, which contains the first // departure-related contents while (!current.classes().contains("corpocentrale")) { current = current.nextSibling(); qDebug() << "skipping to the next element"; if (current.isNull()) break; } // Mark every div as a departure class element; the next corpocentrale // marks the start of the arrivals section qDebug() << "marking departures"; do { if (current.classes().contains("bloccorisultato")) { StationScheduleItem schedule = parseResult(current); if (schedule.isValid()) { m_departureSchedules << schedule; } } current = current.nextSibling(); qDebug() << "marking as departures"; if (current.isNull()) break; } while (!current.classes().contains("corpocentrale")); // Mark everything as an arrival, until reaching the footer while (!current.classes().contains("footer")) { if (current.classes().contains("bloccorisultato")) { StationScheduleItem schedule = parseResult(current); if (schedule.isValid()) { m_arrivalSchedules << schedule; } } current = current.nextSibling(); qDebug() << "marking as arrival"; if (current.isNull()) break; } endResetModel(); emit layoutChanged(); }
void MainWindow::replyFinished (QNetworkReply *reply) { if(reply->error() != QNetworkReply::NoError) { qDebug() << "ERROR!"; qDebug() << reply->errorString(); } else { qDebug()<<"OK"; // qDebug() << reply->header(QNetworkRequest::ContentTypeHeader).toString(); // qDebug() << reply->header(QNetworkRequest::LastModifiedHeader).toDateTime().toString(); // qDebug() << reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); // qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); // qDebug() << reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); //qDebug() << reply->readAll(); QString answer = QString::fromUtf8(reply->readAll()); qDebug()<<"answer"<<answer; int j = 0; QString S; QTime time = QTime::currentTime(); QDate date = QDate::currentDate(); while ((j = answer.indexOf("valcalc_kurs =", j)) != -1) { qDebug() << "Found <musor> tag at index position" << j; for (int i = 17;i <24 ;i++) { S = S + answer[j+i];} qDebug()<<S; // 70.3067 ++j; break; } ui->textBrowser->append(tr("Курс доллара $ на %1,%2 равен:<font color=red>%3</font> rub").arg(time.toString()).arg(date.toString()).arg(S)); j = 0; QString str = date.toString("dd.MM.yyyy"); QString res; qDebug()<<str; while ((j = answer.indexOf(str, j)) != -1) { qDebug() << "Found <musor> tag at index position" << j; for (int i = 40;i <47 ;i++) { res = res + answer[i+j];} qDebug()<<res<<"HE"; // 70.3067 ++j; break; } ui->textBrowser->append("\n"); ui->textBrowser->append(tr("Курс доллара $ на %1 равен: <font color=red>%2</font> rub").arg(str).arg(res)); QWebPage page; page.mainFrame()->setHtml(answer); QWebElement parse = page.mainFrame()->documentElement(); // main body QWebElement result = parse.findFirst("Россия"); //qDebug()<<result.toPlainText(); qDebug()<<parse.toPlainText(); qDebug()<<result.toPlainText(); QFile file("D:/downloader.txt"); file.resize(0); if(file.open(QFile::Append)) { file.write(reply->readAll()); } } reply->deleteLater(); }
void MWBotWin::doTaxi() { if (curTime.date().dayOfWeek() != 1) return; if (opt.taxi.time > curTime) return; QWebElement elm; QWebElement sub; int time; int count; int loop; setBusy(true); loadPage("arbat"); // check taxi chest and take it elm = frm->findFirstElement("div.auto-bombila table.collectbar td.actions button.button"); if (elm.isNull()) { count = 0; } else { count = elm.classes().contains("disabled") ? 0 : 1; } if (count) { sub = elm.findFirst("div.c"); clickElement(sub); log(trUtf8("Забран сундук бомбилы"),"chest.png"); } // check taxi timer, send a car & charge it if it needs elm = frm->findFirstElement("div.auto-bombila table.process td#cooldown"); if (elm.styleProperty("display",QWebElement::ComputedStyle) == "none") { time = 0; } else { time = elm.attribute("timer").toInt(); } if (time != 0) { time += (30 + (random() % 30)); opt.taxi.time = curTime.addSecs(time); log(trUtf8("До следующей бомбилки %0 сек").arg(time),"taxi.png"); } else { do { loop = 0; elm= frm->findFirstElement("div.auto-bombila table.action button.ride-button span.f div.c"); clickElement(elm); elm = frm->findFirstElement("div.alert.alert-error h2#alert-title"); if (elm.isNull()) { elm = frm->findFirstElement("div.auto-bombila table.process td#cooldown"); time = elm.attribute("timer").toInt(); time += 30 + random() % 30; opt.taxi.time = curTime.addSecs(time); log(trUtf8("Авто отправлено бомбить. До следующего раза %0 сек").arg(time),"taxi.png"); } else { elm = frm->findFirstElement("div.alert.alert-error div.actions div.button div.c"); sub = elm.findFirst("span"); count = sub.toPlainText().remove("\"").toInt(); getFastRes(); if (sub.classes().contains("ruda")) { count = (info.ore >= count) ? 1 : 0; } else if (sub.classes().contains("oil")) { count = (info.oil >= count) ? 1 : 0; } else { count = 0; } if (count) { clickElement(elm); log(trUtf8("Машина заправлена"),"taxi.png"); loop = 1; } else { time = 15 * 60; opt.taxi.time = curTime.addSecs(time); log(trUtf8("Не хватает ресурсов для заправки. Ждём 15 мин"),"taxi.png"); } } } while (loop); } setBusy(false); }
void HtmlBookmarksImporter::processElement(const QWebElement &element) { if (element.tagName().toLower() == QLatin1String("h3")) { BookmarksItem *bookmark = BookmarksManager::addBookmark(BookmarksModel::FolderBookmark, QUrl(), element.toPlainText(), getCurrentFolder()); const QString keyword = element.attribute(QLatin1String("SHORTCUTURL")); if (!BookmarksManager::hasKeyword(keyword)) { bookmark->setData(keyword, BookmarksModel::KeywordRole); } if (!element.attribute(QLatin1String("ADD_DATE")).isEmpty()) { const QDateTime time = QDateTime::fromTime_t(element.attribute(QLatin1String("ADD_DATE")).toUInt()); bookmark->setData(time, BookmarksModel::TimeAddedRole); bookmark->setData(time, BookmarksModel::TimeModifiedRole); } setCurrentFolder(bookmark); } else if (element.tagName().toLower() == QLatin1String("a")) { const QUrl url(element.attribute(QLatin1String("href"))); if (!allowDuplicates() && BookmarksManager::hasBookmark(url)) { return; } BookmarksItem *bookmark = BookmarksManager::addBookmark(BookmarksModel::UrlBookmark, url, element.toPlainText(), getCurrentFolder()); const QString keyword = element.attribute(QLatin1String("SHORTCUTURL")); if (!BookmarksManager::hasKeyword(keyword)) { bookmark->setData(keyword, BookmarksModel::KeywordRole); } if (element.parent().nextSibling().tagName().toLower() == QLatin1String("dd")) { bookmark->setData(element.parent().nextSibling().toPlainText(), BookmarksModel::DescriptionRole); } if (!element.attribute(QLatin1String("ADD_DATE")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("ADD_DATE")).toUInt()), BookmarksModel::TimeAddedRole); } if (!element.attribute(QLatin1String("LAST_MODIFIED")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("LAST_MODIFIED")).toUInt()), BookmarksModel::TimeModifiedRole); } if (!element.attribute(QLatin1String("LAST_VISITED")).isEmpty()) { bookmark->setData(QDateTime::fromTime_t(element.attribute(QLatin1String("LAST_VISITED")).toUInt()), BookmarksModel::TimeVisitedRole); } } else if (element.tagName().toLower() == QLatin1String("hr")) { BookmarksManager::addBookmark(BookmarksModel::SeparatorBookmark, QUrl(), QString(), getCurrentFolder()); } const QWebElementCollection descendants = element.findAll(QLatin1String("*")); for (int i = 0; i < descendants.count(); ++i) { if (descendants.at(i).parent() == element) { processElement(descendants.at(i)); } } if (element.tagName().toLower() == QLatin1String("dl")) { goToParent(); } }