R - 从各种 url 导入和格式化多个表

问题描述

我是 R 的新手,所以以下问题可能已经有了一些答案,但我还没有找到与我面临的问题相匹配的解决方案。 我正在尝试从多个网页中获取表格。他们应该在5200左右。 我已经导入了一个来格式化它,但我需要自动化这个过程才能得到它们。 这是网址:

  http://www.tbca.net.br/base-dados/int_composicao_estatistica.PHP?cod_produto=C0195C

我试图通过以下方式找到一种获取所有表格的方法

  url <- paste0("http://www.tbca.net.br/base-dados/int_composicao_estatistica.PHP?cod_produto=",.,sep="" )

但我收到一条错误消息,根据该消息

,

无法读取。 无论如何,一旦我得到它,我既不知道如何自动化格式化过程。 有什么提示吗?

解决方法

以下是您对一种产品的处理方式:

url <- "http://www.tbca.net.br/base-dados/int_composicao_estatistica.php?cod_produto=C0195C"
h <- read_html(url)
tab <- html_table(h,fill=TRUE) %>% 
  as_tibble(.name_repair = "universal")
tab
# # A tibble: 37 x 1
#    ...1$Componente $Unidades $`Valor por 100… $`Desvio padrão` $`Valor Mínimo` $`Valor Máximo` $`Número de dad…
#    <chr>           <chr>     <chr>            <chr>            <chr>           <chr>           <chr>           
#   1 Energia         kJ        578              -                -               -               -               
#   2 Energia         kcal      136              -                -               -               -               
#   3 Umidade         g         65,5             -                -               -               -               
#   4 Carboidrato to… g         33,3             -                -               -               -               
#   5 Carboidrato di… g         32,5             -                -               -               -               
#   6 Proteína        g         0,60             -                -               -               -               
#   7 Lipídios        g         0,26             -                -               -               -               
#   8 Fibra alimentar g         0,84             -                -               -               -               
#   9 Álcool          g         0,00             -                -               -               -               
#   10 Cinzas          g         0,39             -                -               -               -               
#   # … with 27 more rows,and 2 more variables: $Referências <chr>,$`Tipo de dados` <chr>

如果您想抓取所有代码并获取所有表格,您可以使用以下方法进行操作。首先,我们可以设置一个循环来抓取所有链接。通过调查来源,您会发现所有产品代码的 "cod_produto" 属性中都包含 href。您可以使用 xpath 选择器只保留那些包含该字符串的标签。您基本上是在每个页面上循环,直到找到一个没有任何链接的页面。这为您提供了 5203 个链接。

library(glue)
all_links <- NULL
links <- "init"
i <- 1
while(length(links) > 0){
  url <- glue("http://www.tbca.net.br/base-dados/composicao_alimentos.php?pagina={i}&atuald=3")
  h <- read_html(url)
  links <- h %>% html_nodes(xpath = "//a[contains(@href,'cod_produto')]") %>% html_attr("href") %>% unique()
  all_links <- c(all_links,links)
  i <- i+1
}

编辑

接下来,我们可以跟踪每个链接并从中拉出表格,将表格存储在名为 tabs 的列表中。要回答如何在数据中获取产品名称的问题,有两个简单的事情要做。首先是把表格做成数据框,然后在有代号的数据框里做一个变量(我叫code)。二是将列表名称设置为产品代码。下面的答案已经过编辑以做这两件事。

all_links <- unique(all_links)
tabs <- vector(mode="list",length=length(all_links))
for(i in 1:length(all_links)){
  url <- glue("http://www.tbca.net.br/base-dados/{all_links[i]}")
  code <- gsub(".*=(.*)$","\\1",url)
  h <- read_html(url)
  tmp <- html_table(h,fill=TRUE)[[1]]
  tmp <- as.data.frame(tmp)
  tmp$code <- code
  tabs[[i]] <- tmp
  names(tabs)[i] <- code
}