-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCrawler.cpp
88 lines (75 loc) · 1.86 KB
/
Crawler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* Crawler.cpp
*
* Created on: Feb 2, 2013
* Author: vincent
*/
#include "Crawler.h"
#include <QWebFrame>
#include <QWebPage>
#include <QWebElementCollection>
#include <QWebElement>
#include <QApplication>
Crawler::Crawler(QObject *parent) :
QObject(parent), updateMode(false) {
}
Crawler::Crawler(const QString &startUrl) :
startUrl(startUrl) {
Crawler();
}
Crawler::~Crawler() {
}
void Crawler::start() {
if (!startUrl.isEmpty()) {
crawl(startUrl);
}
}
//void Crawler::run() {
// crawlman = new QNetworkAccessManager;
// connect(crawlman, SIGNAL(finished(QNetworkReply*)),
// SLOT(getReply(QNetworkReply*)));
// crawl();
// delete crawlman;
// crawlman = 0;
//}
void Crawler::setStartUrl(const QString &url) {
startUrl = url;
}
void Crawler::getReply(QNetworkReply* reply) {
QByteArray data = reply->readAll();
if (updateMode
|| !Utility::getInstance()->hasUrl(reply->url().toString())) {
} else {
Utility::getInstance()->savePage(reply->url().toString(), data);
}
reply->deleteLater();
foreach(QString url, parseForUrls(data, reply->url().toString())) {
crawl(url);
}
QApplication::processEvents();
}
void Crawler::crawl(const QString& url) {
Utility::getInstance()->getCrawlman()->get(QNetworkRequest(url));
connect(Utility::getInstance()->getCrawlman(),
SIGNAL(finished(QNetworkReply *)),
SLOT(getReply(QNetworkReply *)));
}
QStringList Crawler::parseForUrls(const QByteArray &data,
const QString &baseUrl) {
QWebPage page;
page.mainFrame()->setHtml(data);
QStringList results;
foreach (QWebElement e, page.mainFrame()->findAllElements("a")) {
QString url = e.attribute("href");
if (!url.isEmpty()) {
results.append(QUrl(baseUrl).resolved(url).toString());
}
}
return results;
}
bool Crawler::isUpdateMode() const {
return updateMode;
}
void Crawler::setUpdateMode(bool updateMode) {
this->updateMode = updateMode;
}