Web Scraping con R

Semillero de Ciencia de Datos

2022-12-03

Nuestro objetivo

  • Construir un lector de noticias actuales a través de Google Noticias con R.

Proceso de análisis de datos

¿Qué tipos de datos?

Investigación reproducible

¿Web Scraping?

¿Qué debemos tener en cuenta?

Ejemplo

library(tidyverse) # manipulación de datos
library(rvest)     # web scraping
library(polite)    # verificación de robots.txt para web scraping
library(lubridate) # manipulación de fechas
library(wordcloud) # Nube de palabras
library(tidytext)  # Tokens 
library(tm)        # Manipulación de texto - StopWordss
library(jcolors)   # Colores

¿Scraping desde Google Noticias?

url_colombia <-
  "https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNREZzY3pJU0JtVnpMVFF4T1NnQVAB?hl=es-419&gl=CO&ceid=CO%3Aes-419"

url_colombia %>% 
  bow()
<polite session> https://news.google.com/topics/CAAqJggKIiBDQkFTRWdvSUwyMHZNREZzY3pJU0JtVnpMVFF4T1NnQVAB?hl=es-419&gl=CO&ceid=CO%3Aes-419
    User-agent: polite R package
    robots.txt: 22 rules are defined for 2 bots
   Crawl delay: 5 sec
  The path is scrapable for this user-agent

Títulos de noticias

# Títulos de noticias
titulo_noticia <-
  url_colombia %>%
  read_html() %>%
  html_elements("body") %>%
  html_elements("a.WwrzSb")  %>%
  html_attr("aria-label")

titulo_noticia %>% head(n = 3)
[1] "Pico respiratorio lleva a Minsalud a estudiar el uso obligatorio del tapabocas"
[2] "Navidad con tapabocas: vuelve su uso obligatorio en Colombia"                  
[3] "El tapabocas volvería a ser obligatorio en Colombia | Videos Semana"           

Fuente de noticias

# Fuente
fuente_noticia <- 
  url_colombia %>% 
  read_html() %>% 
  html_elements("body") %>% 
  html_elements("div.MCAGUe") %>% 
  html_text()

fuente_noticia %>% head(n = 3)
[1] "El TiempoMás"      "El ColombianoMás"  "Revista SemanaMás"

Hora de noticia

# Hora
hora_noticia <-
  url_colombia %>%
  read_html() %>%
  html_elements("body") %>%
  html_elements("div.UOVeFe") %>%
  html_text()

hora_noticia %>% head(n = 3)
[1] "Hace 11 horas" "Hace 21 horas" "Hace 15 horas"

¿Más web scraping?

Gracias