【发布时间】:2021-12-16 15:21:58
【问题描述】:
所以我正在尝试从网站获取农场补贴数据,我已经弄清楚如何抓取我正在寻找的内容,现在我正在尝试遍历一个州 (CO) 的所有县以获取这些补贴数据来自各个县。我可以接受 (a) 在循环运行后为每个县创建一个单独的 .csv,或者 (b) 将它们全部编译到一个数据帧中,然后保存为 .csv。
以下是仅针对一个县完成的抓取示例。现在我想编写一个循环,暂时遍历 fips 代码 08003、08005、08007、08009 和 08011(我可以稍后将其推广到 CO 的其他县)。
# Starting with Adams County
library(rvest)
library(dplyr)
library(tidyr)
link = "https://farm.ewg.org/regionsummary.php?fips=08001"
page = read_html(link)
year = page %>% html_nodes("tr~ tr+ tr td:nth-child(1)") %>% html_text()
year
subs = page %>% html_nodes("td:nth-child(3)") %>% html_text()
subs
subsidy_data <- data.frame(subs)
subs = data.frame(do.call("rbind", strsplit(as.character(subsidy_data$subs), "$", fixed = TRUE)))
sub_data <- cbind(year, subs)
sub_data <- sub_data[-c(28),]
cons_sub_rec = page %>% html_nodes("td~ td+ td small:nth-child(1) em") %>% html_text()
cons_sub_rec <- cons_sub_rec[-c(28)]
dis_sub_rec = page %>% html_nodes("small:nth-child(3) em") %>% html_text()
comm_sub_rec = page %>% html_nodes("small:nth-child(5) em") %>% html_text()
ins_sub_rec = page %>% html_nodes("small:nth-child(7) em") %>% html_text()
sub_data <- cbind(year, subs, cons_sub_rec, dis_sub_rec, comm_sub_rec, ins_sub_rec)
sub_data$fips = 8001
write.csv(sub_data,"filepath/ewg_sub_8001.csv", row.names = TRUE)
欢迎提出任何建议!
【问题讨论】:
-
包含几行所需的输出来指导人们通常很有帮助。您可以通过edit 使用SO 拥有的表格工具或使用markdown table generator 生成表格然后输入问题,选择所有表格并按Ctrl + K 缩进并正确显示。