rvest: extract tables with url's instead of text

流过昼夜 提交于 2019-12-04 15:42:36

This shld help get a nice, clean, complete table with the hrefs you want:

library(rvest)
library(tidyverse)

# Helpers
rm_extra <- function(x) { gsub("\r.*$", "", x) }

mk_gd_col_names <- function(x) {
  tolower(x) %>%
    gsub("\ +", "_", .)
}

URL <- "https://aplikacje.nfz.gov.pl/umowy/Provider/Index?ROK=2017&OW=15&ServiceType=03&OrthopedicSupply=False&page=%d"

get_table <- function(page_num = 1) {

  pg <- read_html(sprintf(URL, page_num))

  tab <- html_nodes(pg, "table")

  html_table(tab)[[1]][,-c(1,11)] %>%
    set_names(rm_extra(colnames(.) %>% mk_gd_col_names)) %>%
    mutate_all(funs(rm_extra)) %>%
    mutate(link = html_nodes(tab, xpath=".//td[2]/a") %>% html_attr("href")) %>%
    as_tibble()

}

pb <- progress_estimated(10)
map_df(1:10, function(i) {
  pb$tick()$print()
  get_table(page_num = i)
}) -> full_df

glimpse(full_df)
## Observations: 93
## Variables: 10
## $ kod                         <chr> "150000016", "150005039", "1500046...
## $ nazwa_świadczeniodawcy      <chr> "SAMODZIELNY PUBLICZNY ZAKŁAD OPIE...
## $ miasto                      <chr> "GRODZISK WIELKOPOLSKI", "KALISZ",...
## $ ulica                       <chr> "MOSSEGO 17", "POZNAŃSKA 23", "OS....
## $ kod_pocztowy                <chr> "62065", "62800", "60688", "62510"...
## $ nip                         <chr> "9950036856", "6181976770", "97201...
## $ regon                       <chr> "317760", "251525840", "630804009"...
## $ sumaryczna_kwota_zobowiązań <chr> "8 432 922,00", "332 078,25", "416...
## $ szczegóły                   <chr> "Umowy", "Umowy", "Umowy", "Umowy"...
## $ link                        <chr> "/umowy/Agreements/GetAgreements?R...

full_df
## # A tibble: 93 × 10
##          kod
##        <chr>
## 1  150000016
## 2  150005039
## 3  150004658
## 4  150009135
## 5  150003546
## 6  150000066
## 7  150003556
## 8  150000073
## 9  150003539
## 10 150008909
## # ... with 83 more rows, and 9 more variables:
## #   nazwa_świadczeniodawcy <chr>, miasto <chr>, ulica <chr>,
## #   kod_pocztowy <chr>, nip <chr>, regon <chr>,
## #   sumaryczna_kwota_zobowiązań <chr>, szczegóły <chr>, link <chr>

Here's how to get them from one page. Note that I use the %>% operator, which makes for easier reading, but you could just nest the calls if you prefer

library(rvest)
url<-paste0("https://aplikacje.nfz.gov.pl/umowy/Provider/Index?ROK=2017&OW=15&ServiceType=03&OrthopedicSupply=False&page=1")
page<-html_session(url)
links <- html_nodes(page, 'table') %>% html_nodes("a") %>% html_attr("href")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!