-
Notifications
You must be signed in to change notification settings - Fork 341
/
rvest.Rmd
345 lines (260 loc) · 11.5 KB
/
rvest.Rmd
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
---
title: "Web scraping 101"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Web scraping 101}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, echo=FALSE}
knitr::opts_chunk$set(comment = "#>", collapse = TRUE)
```
This vignette introduces you to the basics of web scraping with rvest.
You'll first learn the basics of HTML and how to use CSS selectors to refer to specific elements, then you'll learn how to use rvest functions to get data out of HTML and into R.
```{r}
library(rvest)
```
## HTML basics
HTML stands for "HyperText Markup Language" and looks like this:
``` {.html}
<html>
<head>
<title>Page title</title>
</head>
<body>
<h1 id='first'>A heading</h1>
<p>Some text & <b>some bold text.</b></p>
<img src='myimg.png' width='100' height='100'>
</body>
```
HTML has a hierarchical structure formed by **elements** which consist of a start tag (e.g. `<tag>`), optional **attributes** (`id='first'`), an end tag[^1] (like `</tag>`), and **contents** (everything in between the start and end tag).
[^1]: A number of tags (including `<p>` and `<li>)` don't require end tags, but I think it's best to include them because it makes seeing the structure of the HTML a little easier.
Since `<` and `>` are used for start and end tags, you can't write them directly.
Instead you have to use the HTML **escapes** `>` (greater than) and `<` (less than).
And since those escapes use `&`, if you want a literal ampersand you have to escape it as `&`.
There are a wide range of possible HTML escapes but you don't need to worry about them too much because rvest automatically handles them for you.
### Elements
All up, there are over 100 HTML elements.
Some of the most important are:
- Every HTML page must be in an `<html>` element, and it must have two children: `<head>`, which contains document metadata like the page title, and `<body>`, which contains the content you see in the browser.
- Block tags like `<h1>` (heading 1), `<p>` (paragraph), and `<ol>` (ordered list) form the overall structure of the page.
- Inline tags like `<b>` (bold), `<i>` (italics), and `<a>` (links) formats text inside block tags.
If you encounter a tag that you've never seen before, you can find out what it does with a little googling.
I recommend the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML) which are produced by Mozilla, the company that makes the Firefox web browser.
### Contents
Most elements can have content in between their start and end tags.
This content can either be text or more elements.
For example, the following HTML contains paragraph of text, with one word in bold.
```{=html}
<p>
Hi! My <b>name</b> is Hadley.
</p>
```
The **children** of a node refers only to elements, so the `<p>` element above has one child, the `<b>` element.
The `<b>` element has no children, but it does have contents (the text "name").
Some elements, like `<img>` can't have children.
These elements depend solely on attributes for their behavior.
### Attributes
Tags can have named **attributes** which look like `name1='value1' name2='value2'`.
Two of the most important attributes are `id` and `class`, which are used in conjunction with CSS (Cascading Style Sheets) to control the visual appearance of the page.
These are often useful when scraping data off a page.
## Reading HTML with rvest
You'll usually start the scraping process with `read_html()`.
This returns a `xml_document`[^2] object which you'll then manipulate using rvest functions:
[^2]: This class comes from the [xml2](https://xml2.r-lib.org) package.
xml2 is a low-level package that rvest builds on top of.
```{r}
html <- read_html("http://rvest.tidyverse.org/")
class(html)
```
For examples and experimentation, rvest also includes a function that lets you create an `xml_document` from literal HTML:
```{r}
html <- minimal_html("
<p>This is a paragraph<p>
<ul>
<li>This is a bulleted list</li>
</ul>
")
html
```
Regardless of how you get the HTML, you'll need some way to identify the elements that contain the data you care about.
rvest provides two options: CSS selectors and XPath expressions.
Here I'll focus on CSS selectors because they're simpler but still sufficiently powerful for most scraping tasks.
## CSS selectors
CSS is short for cascading style sheets, and is a tool for defining the visual styling of HTML documents.
CSS includes a miniature language for selecting elements on a page called **CSS selectors**.
CSS selectors define patterns for locating HTML elements, and are useful for scraping because they provide a concise way of describing which elements you want to extract.
CSS selectors can be quite complex, but fortunately you only need the simplest for rvest, because you can also write R code for more complicated situations.
The four most important selectors are:
- `p`: selects all `<p>` elements.
- `.title`: selects all elements with `class` "title".
- `p.special`: selects all `<p>` elements with `class` "special".
- `#title`: selects the element with the `id` attribute that equals "title".
Id attributes must be unique within a document, so this will only ever select a single element.
If you want to learn more CSS selectors I recommend starting with the fun [CSS dinner](https://flukeout.github.io/) tutorial and then referring to the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors).
Lets try out the most important selectors with a simple example:
```{r}
html <- minimal_html("
<h1>This is a heading</h1>
<p id='first'>This is a paragraph</p>
<p class='important'>This is an important paragraph</p>
")
```
In rvest you can extract a single element with `html_element()` or all matching elements with `html_elements()`.
Both functions take a document[^3] and a css selector:
[^3]: Or another element, more on that shortly.
```{r}
html %>% html_element("h1")
html %>% html_elements("p")
html %>% html_elements(".important")
html %>% html_elements("#first")
```
Selectors can also be combined in various ways using **combinators**.
For example,The most important combinator is " ", the **descendant** combination, because `p a` selects all `<a>` elements that are a child of a `<p>` element.
If you don't know exactly what selector you need, I highly recommend using [SelectorGadget](https://rvest.tidyverse.org/articles/selectorgadget.html), which lets you automatically generate the selector you need by supplying positive and negative examples in the browser.
## Extracting data
Now that you've got the elements you care about, you'll need to get data out of them.
You'll usually get the data from either the text contents or an attribute.
But, sometimes (if you're lucky!), the data you need will be in an HTML table.
### Text
Use `html_text2()` to extract the plain text contents of an HTML element:
```{r}
html <- minimal_html("
<ol>
<li>apple & pear</li>
<li>banana</li>
<li>pineapple</li>
</ol>
")
html %>%
html_elements("li") %>%
html_text2()
```
Note that the escaped ampersand is automatically converted to `&`; you'll only ever see HTML escapes in the source HTML, not in the data returned by rvest.
You might wonder why I used `html_text2()`, since it seems to give the same result as `html_text()`:
```{r}
html %>%
html_elements("li") %>%
html_text()
```
The main difference is how the two functions handle white space.
In HTML, white space is largely ignored, and it's the structure of the elements that defines how text is laid out.
`html_text2()` does its best to follow the same rules, giving you something similar to what you'd see in the browser.
Take this example which contains a bunch of white space that HTML ignores.
```{r}
html <- minimal_html("<body>
<p>
This is
a
paragraph.</p><p>This is another paragraph.
It has two sentences.</p>
")
```
`html_text2()` gives you what you expect: two paragraphs of text separated by a blank line.
```{r}
html %>%
html_element("body") %>%
html_text2() %>%
cat()
```
Whereas `html_text()` returns the garbled raw underlying text:
```{r}
html %>%
html_element("body") %>%
html_text() %>%
cat()
```
### Attributes
Attributes are used to record the destination of links (the `href` attribute of `<a>` elements) and the source of images (the `src` attribute of the `<img>` element):
```{r}
html <- minimal_html("
<p><a href='https://en.wikipedia.org/wiki/Cat'>cats</a></p>
<img src='https://cataas.com/cat' width='100' height='200'>
")
```
The value of an attribute can be retrieved with `html_attr()`:
```{r}
html %>%
html_elements("a") %>%
html_attr("href")
html %>%
html_elements("img") %>%
html_attr("src")
```
Note that `html_attr()` always returns a string, so you may need to post-process with `as.integer()`/`readr::parse_integer()` or similar.
```{r}
html %>%
html_elements("img") %>%
html_attr("width")
html %>%
html_elements("img") %>%
html_attr("width") %>%
as.integer()
```
### Tables
HTML tables are composed four main elements: `<table>`, `<tr>` (table row), `<th>` (table heading), and `<td>` (table data).
Here's a simple HTML table with two columns and three rows:
```{r}
html <- minimal_html("
<table>
<tr>
<th>x</th>
<th>y</th>
</tr>
<tr>
<td>1.5</td>
<td>2.7</td>
</tr>
<tr>
<td>4.9</td>
<td>1.3</td>
</tr>
<tr>
<td>7.2</td>
<td>8.1</td>
</tr>
</table>
")
```
Because tables are a common way to store data, rvest includes the handy `html_table()` which converts a table into a data frame:
```{r}
html %>%
html_node("table") %>%
html_table()
```
## Element vs elements
When using rvest, your eventual goal is usually to build up a data frame, and you want each row to correspond some repeated unit on the HTML page.
In this case, you should generally start by using `html_elements()` to select the elements that contain each observation then use `html_element()` to extract the variables from each observation.
This guarantees that you'll get the same number of values for each variable because `html_element()` always returns the same number of outputs as inputs.
To illustrate this problem take a look at this simple example I constructed using a few entries from `dplyr::starwars`:
```{r}
html <- minimal_html("
<ul>
<li><b>C-3PO</b> is a <i>droid</i> that weighs <span class='weight'>167 kg</span></li>
<li><b>R2-D2</b> is a <i>droid</i> that weighs <span class='weight'>96 kg</span></li>
<li><b>Yoda</b> weighs <span class='weight'>66 kg</span></li>
<li><b>R4-P17</b> is a <i>droid</i></li>
</ul>
")
```
If you try to extract name, species, and weight directly, you end up with one vector of length four and two vectors of length three, and no way to align them:
```{r}
html %>% html_elements("b") %>% html_text2()
html %>% html_elements("i") %>% html_text2()
html %>% html_elements(".weight") %>% html_text2()
```
Instead, use `html_elements()` to find a element that corresponds to each character, then use `html_element()` to extract each variable for all observations:
```{r}
characters <- html %>% html_elements("li")
characters %>% html_element("b") %>% html_text2()
characters %>% html_element("i") %>% html_text2()
characters %>% html_element(".weight") %>% html_text2()
```
`html_element()` automatically fills in `NA` when no elements match, keeping all of the variables aligned and making it easy to create a data frame:
```{r}
data.frame(
name = characters %>% html_element("b") %>% html_text2(),
species = characters %>% html_element("i") %>% html_text2(),
weight = characters %>% html_element(".weight") %>% html_text2()
)
```