author | Christian Urban <christian dot urban at kcl dot ac dot uk> |
Fri, 22 Nov 2013 16:56:51 +0000 | |
changeset 198 | f54972b0f641 |
parent 112 | 95ee5cc5c05d |
child 242 | 35104ee14f87 |
permissions | -rw-r--r-- |
101
4758a6155878
links
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
99
diff
changeset
|
1 |
// A crawler which checks whether there |
4758a6155878
links
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
99
diff
changeset
|
2 |
// are problems with links in web-pages |
4758a6155878
links
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
99
diff
changeset
|
3 |
|
1 | 4 |
import io.Source |
5 |
import scala.util.matching.Regex |
|
96
9fcd3de53c06
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
95
diff
changeset
|
6 |
import scala.util._ |
1 | 7 |
|
112
95ee5cc5c05d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
101
diff
changeset
|
8 |
// gets the first 10K of a web-page |
99
91145f6d9b0e
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
96
diff
changeset
|
9 |
def get_page(url: String) : String = { |
96
9fcd3de53c06
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
95
diff
changeset
|
10 |
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
|
11 |
{ println(s" Problem with: $url"); ""} |
99
91145f6d9b0e
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
96
diff
changeset
|
12 |
} |
1 | 13 |
|
14 |
// regex for URLs |
|
15 |
val http_pattern = """\"https?://[^\"]*\"""".r |
|
16 |
||
101
4758a6155878
links
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
99
diff
changeset
|
17 |
// drops the first and last character from a string |
1 | 18 |
def unquote(s: String) = s.drop(1).dropRight(1) |
19 |
||
20 |
def get_all_URLs(page: String) : Set[String] = { |
|
112
95ee5cc5c05d
added
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
101
diff
changeset
|
21 |
http_pattern.findAllIn(page).map(unquote).toSet |
1 | 22 |
} |
23 |
||
24 |
// naive version - seraches until a given depth |
|
25 |
// visits pages potentially more than once |
|
26 |
def crawl(url: String, n: Int) : Unit = { |
|
27 |
if (n == 0) () |
|
28 |
else { |
|
95
dbe49327b6c5
added new stuff
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
93
diff
changeset
|
29 |
println(s"Visiting: $n $url") |
1 | 30 |
for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1) |
31 |
} |
|
32 |
} |
|
33 |
||
3 | 34 |
// staring URL for the crawler |
35 |
val startURL = """http://www.inf.kcl.ac.uk/staff/urbanc/""" |
|
7 | 36 |
//val startURL = """http://www.inf.kcl.ac.uk/staff/mml/""" |
37 |
||
1 | 38 |
crawl(startURL, 2) |
39 |