r - 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
}
推荐阅读
- javascript - DiscordJS - 有没有办法重新启动反应收集器?
- html - CSS:加载SVG并相对于其元素定位
- xamarin - Xamarin Forms Plugin.BLE 找不到任何设备
- azure-stream-analytics - Case 语句中的 select 语句
- ios - Swift parse json from API - 无法读取数据,因为它的格式不正确
- sql - SQL - 将工作分配给工人 - 替代循环?
- python - 在 valueerror 循环中中断导致错误
- r - 使用“plot.matrix”绘图时如何为矩阵中的一组单元格着色
- stripe-payments - 如何创建订阅(使用 on_behalf_of 参数)与连接帐户的目的地转移?
- python - 执行字符串格式化时出现值错误 {Python, Windows 10}