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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
| package netsur2;
import java.net.URL;
import java.util.*;
import java.util.regex.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
// http://pageperso.lif.univ-mrs.fr/~andreea.dragut/enseignementWebMining/r/tp1.html
public class SimpleCrawler {
public static SimpleCrawler factory(String urlFourni) throws Throwable {
// on se prend la liste des URLs a parcourir
Queue<CrawlerUrl> urlQueue = new LinkedList<CrawlerUrl>();
// l'url de demarrage du crawler
String url = urlFourni;
// on le met dans la liste
CrawlerUrl cr=new CrawlerUrl(url, 0);
urlQueue.add(cr);
Applet_VeilleConcurentielle.console("Demarrage du crawler sur "+url+" / Start of crawler on "+url);
SimpleCrawler crawler=new SimpleCrawler(urlQueue,100,3,100L);
String[] ext=".css,.js,.bmp,.gif,.jpeg,.jpg,.png,.tif,.tiff,.mid,.mp2,.mp3,.mp4,.wav,.avi,.mov,.mpeg,.ram,.m4v,.pdf,.rm,.smil,.wmv,.swf,.wma,.zip,.rar,.gz".toLowerCase().split(",");
crawler.extensions=new ArrayList<String>(Arrays.asList(ext));
crawler.domaineSite=cr.getURL().getHost();
return crawler;
}
private static final String USER_AGENT = "User-agent:";
private static final String DISALLOW = "Disallow:";
public long maxNumberUrls;
public long delayBetweenUrls;
public int maxDepth;
public String userAgent="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
public String regexTitre;
public String regexPrix;
public int numMasqueTitre;
public int numMasquePrix;
public ArrayList<String> extensions=new ArrayList<String>();
private Map<String, CrawlerUrl> visitedUrls = null;
private Map<String, Collection<String>> sitePermissions = null;
private String domaineSite;
public Queue<CrawlerUrl> urlQueue = null;
public SimpleCrawler(Queue<CrawlerUrl> urlQueue, int maxNumberUrls,
int maxDepth, long delayBetweenUrls)
throws Exception {
//System.out.println("SimpleCrawler::SimpleCrawler()");
this.urlQueue = urlQueue;
this.maxNumberUrls = maxNumberUrls;
this.delayBetweenUrls = delayBetweenUrls;
this.maxDepth = maxDepth;
this.visitedUrls = new HashMap<String, CrawlerUrl>();
this.sitePermissions = new HashMap<String, Collection<String>>();
}
public void crawl() throws Exception { // methode principale
while (continueCrawling()) { // tant qu'on a des URLs a parcourir
// et qu'on remplit les conditions (profondeur, n max, etc.)
CrawlerUrl url = getNextUrl(); // au suivant
if (url != null) {
printCrawlInfo(); // affichage+sauvgrd dans crawlStatistics
getContent(url); // recuperation du contenu depuis le web
saveContent(url); // sauvgrd texte dans download_<docId>.txt
// du titre dans title_<docId>.txt, etc.
addUrlsToUrlQueue(url); // liens sortants dans la queue
saveLinks(url); //liens sortants -> outlinkurls_<docId>.txt
Thread.sleep(this.delayBetweenUrls); // pour ne pas assommer
// les serveurs
}
}
generateOutlinksIds(); // lecture de crawl.txt avec construction de
// la table de hachage et puis pour chaque
// outlinkurls_<docId>.txt, ecriture de
// outlinks_<docId>.txt qui contient les
// docIds atteignables
}
private boolean continueCrawling() { // savoir si on peut continuer
boolean qContinue = (!urlQueue.isEmpty()) &&
(getNumberOfUrlsVisited() < this.maxNumberUrls);
//System.out.println("Deciding whether to continue crawling ... " + String . valueOf(qContinue) + " ..");
return (qContinue);
}
private CrawlerUrl getNextUrl() { // obtenir l'URL suivant a explorer
CrawlerUrl nextUrl = null;
while ((nextUrl == null) && (!urlQueue.isEmpty())) {
CrawlerUrl crawlerUrl = this.urlQueue.remove();
if (doWeHavePermissionToVisit(crawlerUrl)
&& (!isUrlAlreadyVisited(crawlerUrl))
&& isDepthAcceptable(crawlerUrl)) {
nextUrl = crawlerUrl;
//System.out.println("Le prochain url a visiter est "+nextUrl);
}
}
return nextUrl;
}
// maintenant il y a quelques methodes auxiliaires
private void printCrawlInfo() throws Exception {
int nb=getNumberOfUrlsVisited();
if(nb!=0 && nb % 100 ==0)
{
Applet_VeilleConcurentielle.console("Crawling en cours... "+nb+" URL analysés / Crawling in progress... "+nb+" URL visited -- "+Fc.aujourdhui("dd/MM/yyyy HH:mm:ss"));
}
/* StringBuilder sb = new StringBuilder();
sb.append("Queue length = ").append(this.urlQueue.size()).append(
" visited urls=").append(getNumberOfUrlsVisited()).append(
" site permissions=").append(this.sitePermissions.size());
System.out.println(sb.toString()); */
}
private int getNumberOfUrlsVisited() {
return this.visitedUrls.size();
}
private boolean isDepthAcceptable(CrawlerUrl crawlerUrl) {
return crawlerUrl.getDepth() <= this.maxDepth;
}
private boolean isUrlAlreadyVisited(CrawlerUrl crawlerUrl) {
if ((crawlerUrl.isVisited())
|| (this.visitedUrls.containsKey(crawlerUrl.getUrlString()))) {
return true;
}
return false;
}
public boolean doWeHavePermissionToVisit(CrawlerUrl crawlerUrl) {
if (crawlerUrl == null) {
return false;
}
if (!crawlerUrl.isCheckedForPermission()) {
crawlerUrl.setAllowedToVisit(
computePermissionForVisiting(crawlerUrl));
}
// We need to check
return crawlerUrl.isAllowedToVisit();
}
private boolean computePermissionForVisiting(CrawlerUrl crawlerUrl) {
URL url = crawlerUrl.getURL();
boolean retValue = (url != null);
if (retValue) {
String host = url.getHost();
if(!host.equals(domaineSite)) return false; //rester dans le domaine
if(!crawlerUrl.extensionAutoriser(extensions)) return false; //extensions autorisées
String port = "";
int portN = url.getPort();
if(portN > -1) {
port = ":" + String.valueOf(portN);
}
Collection<String> disallowedPaths=this.sitePermissions.get(host);
if (disallowedPaths == null) {
disallowedPaths =
parseRobotsTxtFileToGetDisallowedPaths(host+port);
}
// On itere pour tous les chemins interdits (disallowed paths)
String path = url.getPath();
if(path!="" && path!="/")
{
for (String disallowedPath : disallowedPaths) {
if (path.equals(disallowedPath)) {
retValue = false;
}
}
}
}
return retValue;
}
private Collection<String> parseRobotsTxtFileToGetDisallowedPaths(
String host) {
String robotFilePath = getContent("http://" + host + "/robots.txt");
Collection<String> disallowedPaths = new ArrayList<String>();
if (robotFilePath != null) {
Pattern p = Pattern.compile(USER_AGENT);
String[] permissionSets = p.split(robotFilePath);
String permissionString = "";
for (String permission : permissionSets) {
if (permission.trim().startsWith("*")) {
permissionString = permission.substring(1);
}
}
p = Pattern.compile(DISALLOW);
String[] items = p.split(permissionString);
for (String s : items) {
disallowedPaths.add(s.trim());
// System.out.println(s.trim());
}
}
this.sitePermissions.put(host, disallowedPaths);
return disallowedPaths;
}
private String getContent(String urlString) {
return getContent(new CrawlerUrl(urlString, 0));
}
private String getContent(CrawlerUrl url) { // methode essentielle --
// recuperation du fichier .html depuis le serveur
HttpClient httpclient = new DefaultHttpClient();
String userAgent = this.userAgent;
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
String text = new String();
try {
HttpGet httpget = new HttpGet(url.getUrlString()); //construction
// de l'objet qui fera la connexion
//System.out.println("executing request " + httpget.getURI());
// construction de l'objet qui gerera le dialogue avec le serveur
ResponseHandler<String> responseHandler =
new BasicResponseHandler();
try {
text = httpclient.execute(httpget, responseHandler); //et on y va
} catch(Exception e) {}
}
catch(Throwable t) {
System.out.println("Echec du chargement de "+url.getUrlString()+" "+ t . toString());
//t . printStackTrace();
}
finally {
// Lorsque on n'a plus besoin de l'objet de type HttpClient
// on ferme la connexion pour eliberer rapidement les resources
// systeme qu'on avait monopolisees
httpclient.getConnectionManager().shutdown();
}
markUrlAsVisited(url); // on marque l'URL
url . setRawContent(text); // on donne le texte HTML brut au parseur
// appele dans la classe CrawlerUrl -- qui en extrait le texte,
// le titre, les liens sortants, etc. (apres avoir parse le texte
// HTML ainsi fourni)
return text;
}
private void markUrlAsVisited(CrawlerUrl url) {
this.visitedUrls.put(url.getUrlString(), url);
url.setIsVisited();
}
private void saveContent(CrawlerUrl url) throws Exception {
String content = url . getHTML();
//String title = url . getTitle();
String urlPage = url . getUrlString();
String titre=Fc.trouverTxt(regexTitre, content,numMasqueTitre);
String prix=Fc.trouverTxt(regexPrix, content,numMasquePrix);
if(titre!=null && titre!="" && prix!=null && prix!="")
{
Produit pr=new Produit();
pr.setName(titre);
pr.setPrix(prix);
pr.lien=urlPage;
if(Applet_VeilleConcurentielle.pileProduitCourante!=null) Applet_VeilleConcurentielle.pileProduitCourante.aj(pr);
}
url.raz();
}
private void saveLinks(CrawlerUrl url) throws Exception {
//sauvegarder liens
}
private void addUrlsToUrlQueue(CrawlerUrl url) {
Collection<String> urlStrings = url . getLinks();
int depth = url.getDepth() + 1;
for (String urlString : urlStrings) {
if (!this.visitedUrls.containsKey(urlString)) {
this.urlQueue.add(new CrawlerUrl(urlString, depth));
}
}
}
private void generateOutlinksIds() throws Exception{
//la méthode semble innutile
}
} |
Partager