scala/crawler2.scala
changeset 92 e85600529ca5
parent 7 73cf4406b773
equal deleted inserted replaced
91:47f86885d481 92:e85600529ca5
       
     1 import io.Source
       
     2 import scala.util.matching.Regex
       
     3 
       
     4 // gets the first ~10K of a page
       
     5 def get_page(url: String) : String = { 
       
     6   try {
       
     7     Source.fromURL(url).take(10000).mkString  
       
     8   }
       
     9   catch {
       
    10     case e => {
       
    11       println("  Problem with: " + url)
       
    12       ""
       
    13     }
       
    14   }
       
    15 }
       
    16 
       
    17 // staring URL for the crawler
       
    18 val startURL = """http://www.inf.kcl.ac.uk/staff/urbanc/"""
       
    19 
       
    20 // regex for URLs
       
    21 val http_pattern = """\"https?://[^\"]*\"""".r
       
    22 val my_urls = """urbanc""".r
       
    23 
       
    24 def unquote(s: String) = s.drop(1).dropRight(1)
       
    25 
       
    26 def get_all_URLs(page: String) : Set[String] = {
       
    27   (http_pattern.findAllIn(page)).map { unquote(_) }.toSet
       
    28 }
       
    29 
       
    30 // naive version - seraches until a given depth
       
    31 // visits pages potentially more than once
       
    32 def crawl(url: String, n: Int) : Unit = {
       
    33   if (n == 0) ()
       
    34   else if (my_urls.findFirstIn(url) == None) ()
       
    35   else {
       
    36     println("Visiting: " + n + " " + url)
       
    37     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
       
    38   }
       
    39 }
       
    40 
       
    41 // can now deal with depth 3
       
    42 // start on command line
       
    43 crawl(startURL, 4)
       
    44