首页 > 解决方案 > 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="" )

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

 , .,

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

标签: rurlweb-scrapingimport-table

解决方案


以下是针对一种产品的方法:

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
}


推荐阅读