-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathservel_scraping_presidenciales.R
More file actions
178 lines (120 loc) · 4.09 KB
/
Copy pathservel_scraping_presidenciales.R
File metadata and controls
178 lines (120 loc) · 4.09 KB
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
library(dplyr)
library(rvest)
library(purrr)
library(tidyr)
library(lubridate)
library(stringr)
library(RSelenium)
library(readr)
source("funciones.R")
esperas = 2
# abrir server ----
if (exists("driver")) driver$server$stop()
driver <- rsDriver(browser = "firefox",
port = 4561L, verbose = F,
chromever = NULL, phantomver = NULL)
remote_driver <- driver[["client"]]
# configurar sitio ----
remote_driver$navigate("https://elecciones.servel.cl")
Sys.sleep(esperas*1.5)
# navegar ----
# apretar botón presidente
remote_driver$
findElement("xpath",
'//*[@id="4"]')$
clickElement()
Sys.sleep(tiempo_aleatorio(esperas))
# apretar botón división geográfica
remote_driver$
findElement("css selector",
"#filtros_boton > div:nth-child(3)")$
clickElement()
Sys.sleep(tiempo_aleatorio(esperas))
# región metropolitana
remote_driver$
findElement("css selector",
".p-6 > div:nth-child(3) > div:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > select:nth-child(2) > option:nth-child(8)")$
clickElement()
Sys.sleep(tiempo_aleatorio(esperas))
# obtener comunas ----
sitio_comunas <- remote_driver$getPageSource()
# obtener opciones del selector de comunas
comunas <- sitio_comunas[[1]] |>
read_html() |>
html_elements(".p-6 > div:nth-child(3) > div:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(3) > select:nth-child(2)") |>
html_elements("option") |>
# html_attr("data-id")
html_text()
comunas
message("cantidad de comunas: ", length(comunas))
Sys.sleep(esperas)
# loop scraping ----
## seleccionar comunas ----
# # pruebas
# lista_comunas <- c(3:10)
# # todas las comunas
lista_comunas <- c(2:length(comunas)) # el 1 es "seleccionar opción"
# loop ----
message("obteniendo ", length(lista_comunas), " comunas")
tabla <- map(lista_comunas, \(comuna_n) {
# comuna_n <- 2
# message("obteniendo comuna: ", comunas[comuna_n])
tryCatch({
# seleccionar región metropolitana para reiniciar selector de provincia
remote_driver$
findElement("css selector",
".p-6 > div:nth-child(3) > div:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > select:nth-child(2) > option:nth-child(8)")$
clickElement()
# seleccionar opción del dropdown
remote_driver$
findElement("css selector",
paste0("div.mb-10:nth-child(3) > div:nth-child(1) > div:nth-child(1) > div:nth-child(3) > select:nth-child(2) > option:nth-child(", comuna_n, ")"))$
clickElement()
# esperar
Sys.sleep(tiempo_aleatorio(esperas/2))
# obtener el código de fuente del sitio
sitio <- remote_driver$getPageSource()
sitio_codigo_fuente <- sitio[[1]] |>
read_html()
# extraer tabla
tabla <- sitio_codigo_fuente |>
html_table(convert = FALSE)
# confirmar
stopifnot("resultados sin filas" = nrow(tabla[[3]]) >= 8)
# extraer datos de mesas
texto_mesas <- sitio_codigo_fuente |>
html_elements("p.text-subtitulo:nth-child(6)") |>
html_text()
# confirmar
if (length(texto_mesas) == 0) warning("sin texto de mesas")
# extraer nombre de comuna
nombre_comuna <- sitio_codigo_fuente |>
html_elements(xpath = '/html/body/div/div/main/div/div/div[2]/div/div/div[1]/div/div[1]/div[2]/p[1]') |>
html_text()
# confirmar
stopifnot("sin nombre de comuna" = length(nombre_comuna) == 1)
# agregar la columna de comuna y las de mesas
tabla_2 <- tabla[[3]] |>
mutate(comuna_id = comuna_n,
comuna = nombre_comuna,
mesas_texto = texto_mesas)
message(nombre_comuna)
return(tabla_2)
}, error = function(e) {
warning(paste("error en comuna", comunas[comuna_n]), e)
return(NULL)
}
)
})
# resultado ----
tabla
tabla |>
bind_rows() |>
distinct(comuna)
beepr::beep()
# guardar ----
write_rds(tabla,
paste0("datos/scraping/presidenciales/resultados_", now(), ".rds"))
# cerrar server ----
driver$server$stop()
message("OK")