-
Notifications
You must be signed in to change notification settings - Fork 4
/
Chapter02.R
57 lines (36 loc) · 1.22 KB
/
Chapter02.R
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
# 『Rによるデータ自動収集 -- Webスクレイピングとテキストマイニングの実践ガイド --』
## 第 5 章 HTML
### 2.4.1 パーサーとは
url <- "http://www.r-datacollection.com/materials/html/fortunes.html"
fortunes <- readLines(con = url)
fortunes
#### 2.4.1 DOM
library(XML)
parsed_fortunes <- htmlParse(file = url)
print(parsed_fortunes)
### 2.4.2 ハンドラ関数の指定
h1 <- list("body" = function(x){NULL})
parsed_fortunes <- htmlTreeParse(url, handlers = h1, asTree = TRUE)
parsed_fortunes$children
### 2.4.2 総称ハンドラ
h2 <- list(
startElement = function(node, ...){
name <- xmlName(node)
if(name %in% c("div", "title")){NULL}else{node}
},
comment = function(node){NULL}
)
parsed_fortunes <- htmlTreeParse(file = url, handlers = h2, asTree = TRUE)
parsed_fortunes
### 2.4.3 クロージャーとしてのハンドラ関数
getItalics = function() {
i_container = character()
list(i = function(node, ...) {
i_container <<- c(i_container, xmlValue(node))
},
returnI = function() i_container)
}
h3 <- getItalics()
invisible(htmlTreeParse(url, handlers = h3))
# コード部分での注釈は # 1 個で良い
h3$returnI()