author | Christian Urban <christian dot urban at kcl dot ac dot uk> |
Wed, 25 Sep 2013 20:35:54 +0100 | |
changeset 99 | 91145f6d9b0e |
parent 96 | 9fcd3de53c06 |
child 101 | 4758a6155878 |
permissions | -rw-r--r-- |
1 | 1 |
import io.Source |
2 |
import scala.util.matching.Regex |
|
96
9fcd3de53c06
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
95
diff
changeset
|
3 |
import scala.util._ |
1 | 4 |
|
5 |
// gets the first ~10K of a page |
|
99
91145f6d9b0e
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
96
diff
changeset
|
6 |
def get_page(url: String) : String = { |
96
9fcd3de53c06
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
95
diff
changeset
|
7 |
Try(Source.fromURL(url).take(10000).mkString) getOrElse |
9fcd3de53c06
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
95
diff
changeset
|
8 |
{ println(s" Problem with: $url"); ""} |
99
91145f6d9b0e
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
96
diff
changeset
|
9 |
} |
1 | 10 |
|
11 |
// regex for URLs |
|
12 |
val http_pattern = """\"https?://[^\"]*\"""".r |
|
13 |
||
14 |
def unquote(s: String) = s.drop(1).dropRight(1) |
|
15 |
||
16 |
def get_all_URLs(page: String) : Set[String] = { |
|
17 |
(http_pattern.findAllIn(page)).map { unquote(_) }.toSet |
|
18 |
} |
|
19 |
||
20 |
// naive version - seraches until a given depth |
|
21 |
// visits pages potentially more than once |
|
22 |
def crawl(url: String, n: Int) : Unit = { |
|
23 |
if (n == 0) () |
|
24 |
else { |
|
95
dbe49327b6c5
added new stuff
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
93
diff
changeset
|
25 |
println(s"Visiting: $n $url") |
1 | 26 |
for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1) |
27 |
} |
|
28 |
} |
|
29 |
||
3 | 30 |
// staring URL for the crawler |
31 |
val startURL = """http://www.inf.kcl.ac.uk/staff/urbanc/""" |
|
7 | 32 |
//val startURL = """http://www.inf.kcl.ac.uk/staff/mml/""" |
33 |
||
3 | 34 |
|
35 |
// call on the command line |
|
1 | 36 |
crawl(startURL, 2) |
37 |
||
95
dbe49327b6c5
added new stuff
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
93
diff
changeset
|
38 |
crawl("""http://www.inf.kcl.ac.uk/staff/urbanc/bsc-projects-13.html""", 2) |