-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraping_secretaria_funcion.R
More file actions
158 lines (113 loc) · 4.85 KB
/
Copy pathscraping_secretaria_funcion.R
File metadata and controls
158 lines (113 loc) · 4.85 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
# Ejercicios para módulo 1 ------------------------------------------------
# Módulo 1: Técnicas y selección de elementos.
packages <- c("tidyverse", "janitor", "janitor", "rvest", "writexl",
"glue")
package.check <- lapply(
packages,
FUN = function(x) {
if (!require(x, character.only = TRUE)) {
install.packages(x, dependencies = TRUE)
library(x, character.only = TRUE)
}
}
)
# Secretaría Función Pública ----------------------------------------------
# 1. Extraer URL ----------------------------------------------------------
# Objetivo: Identificar elementos claves de una estructura HTML, seleccionando
# elementos específicos del sitio de donde se quiere extraer información.
url <- "https://www.gob.mx/sfp/es/archivo/prensa"
robotstxt::paths_allowed(url)
rvest::session(url)
prensa <- rvest::read_html(url)
# 2. Ver clases de HTML ---------------------------------------------------
# Objetivo: Identificar nodos y atributos de una composición HTML.
prensa %>%
rvest::html_nodes("*") %>%
rvest::html_attr("class") %>%
base::unique()
# 3. Extraer nodos e información deseada ----------------------------------
# Objetivo: Diseñar técnicas para extraer información de los nodos y atributos deseados.
titulares <- prensa %>%
rvest::html_nodes("article h2") %>%
rvest::html_text(trim = TRUE) %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_extract(value, "^[^\\\\]+"),
value = stringr::str_squish(value)) %>%
dplyr::rename(titular = value)
enlaces <- prensa %>%
rvest::html_nodes("h2 > a") %>%
rvest::html_attr("href") %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_replace_all(value, "\\\\\"", "")) %>%
dplyr::rename(enlace = value)
fecha <- prensa %>%
rvest::html_nodes("time") %>%
rvest::html_attr("datetime") %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_replace_all(value, "\\\\\"", "")) %>%
dplyr::rename(fecha = value)
# 3. Crear una matriz de datos -----------------------------------------------
# Objetivo: Construir una matriz de datos a partir de la información recopilada.
matriz_datos <- tibble::tibble(fecha,
titulares,
enlaces) %>%
janitor::clean_names() %>%
dplyr::mutate(url_acceso = paste0("https://www.gob.mx", enlace)) %>%
dplyr::select(-enlace)
# 4. Guardar en fichero Excel ---------------------------------------------
# Objetivo: Crear un flujo que permita almacenar la información extraída en un fichero Excel.
if(!dir.exists("noticias_secretaria")) dir.create("noticias_secretaria")
anio <- lubridate::year(Sys.Date())
etiqueta <- "Secretaría Función Pública"
writexl::write_xlsx(x = matriz_datos,
col_names = TRUE,
path = paste0("noticias_secretaria/",
glue::glue('{anio} {etiqueta}'), ".xlsx"))
# 5. Implementación de procesos iterativos --------------------------------
# Objetivo: Escalar a una función automatizada para llevar a cabo un proceso iterativo que seleccione
# los elementos de la web a partir patrón en particular.
pagina <- "https://www.gob.mx/sfp/es/archivo/prensa"
patron_pagina <- "?page="
noticias_secretaria <- function(n_pagina){
Sys.sleep(time = 5)
pagina <- "https://www.gob.mx/sfp/es/archivo/prensa"
patron_pagina <- "?page="
concatenar_patron <- paste0(pagina, patron_pagina, n_pagina)
estructura_html <- rvest::read_html(concatenar_patron)
titulares <- estructura_html %>%
rvest::html_nodes("article h2") %>%
rvest::html_text(trim = TRUE) %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_extract(value, "^[^\\\\]+"),
value = stringr::str_squish(value)) %>%
dplyr::rename(titular = value)
enlaces <- estructura_html %>%
rvest::html_nodes("h2 > a") %>%
rvest::html_attr("href") %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_replace_all(value, "\\\\\"", "")) %>%
dplyr::rename(enlace = value)
fecha <- estructura_html %>%
rvest::html_nodes("time") %>%
rvest::html_attr("datetime") %>%
tibble::as_tibble() %>%
dplyr::mutate(value = str_replace_all(value, "\\\\\"", "")) %>%
dplyr::rename(fecha = value)
matriz_datos <- tibble::tibble(fecha,
titulares,
enlaces) %>%
janitor::clean_names() %>%
dplyr::mutate(url_acceso = paste0("https://www.gob.mx", enlace)) %>%
dplyr::select(-enlace)
return(matriz_datos)
}
noticias_secretaria(n_pagina = 2)
iterar_funcion <- purrr::map_df(1:2, noticias_secretaria)
paginas <- seq(from = 1, to = 1, by = 1)
resultados <- list()
for (i in paginas) {
x <- noticias_secretaria(i)
resultados[[i]] <- x
}
resultado_combinado <- dplyr::bind_rows(resultados)
lapply(paginas, noticias_secretaria)