Scrape table from webpage using R

snip snip

R
RStudio
Author

Nick Twort

Published

29 Sep 2023

Here’s a snippet for scraping a table from a webpage. Copy the URL (or enter it after) and execute the snippet1 with scrape Shift Tab.

snippet scrape
    library(tidyverse)
    library(rvest)
    library(magrittr)
    library(janitor)
    
    url <- "${1:`r ifelse(grepl('^http', readClipboard()), readClipboard(), 'url')`}"
    read_html(url) |>
        html_nodes("table") |>
        html_table(fill = TRUE) |>
        extract2(1) |>
        as_tibble() |>
        clean_names()
Attribution

Thanks for the tip, Vivek K.

Footnotes

  1. To add this to your snippets, run usethis::edit_rstudio_snippets() and paste in the snippet below.↩︎