使用循环通过网络抓取创建 table

Creating a table by web-scraping using a loop

我正在尝试网络抓取 tax-rates.org 以获得德克萨斯州每个县的平均税率。我在一个 csv 文件中有一个包含 255 个县的列表,我将其导入为 "TX_counties",它是一个单列 table。我必须为每个县创建 URL 作为字符串,所以我使用 [i,1] 将 d1 设置为第一个单元格,然后将其连接成 URL 字符串,执行抓取,然后添加+1 到 [i] 使其转到下一个县名的第二个单元格,然后该过程继续。

问题是我不知道如何将抓取结果存储到 "growing list" 中,然后我想将其制作成 table 并在最后保存到 .csv 文件。我一次只能抓取一个县,然后它会自己重新写入。

有什么想法吗? (对 R 相当陌生,一般来说是抓取)

i <- 1
for (i in 1:255) {

  d1 <- as.character(TX_counties[i,1])

  uri.seed <- paste(c('http://www.tax-rates.org/texas/',d1,'_county_property_tax'), collapse='')

  html <- htmlTreeParse(file = uri.seed, isURL=TRUE, useInternalNodes = TRUE)

  avg_taxrate <- sapply(getNodeSet(html, "//div[@class='box']/div/div[1]/i[1]"), xmlValue)

  t1 <- data.table(d1,avg_taxrate)

  i <- i+1

}

write.csv(t1,"2015_TX_PropertyTaxes.csv")
library(RCurl)
library(XML)
tx_c <- c("anderson", "andrews")

res <- sapply(1:2, function(x){
    d1 <- as.character(tx_c[x])
    uri.seed <- paste(c('http://www.tax-rates.org/texas/',d1,'_county_property_tax'), collapse='')
    html <- htmlTreeParse(file = uri.seed, isURL=TRUE, useInternalNodes = TRUE)
    avg_taxrate <- sapply(getNodeSet(html, "//div[@class='box']/div/div[1]/i[1]"), xmlValue)
    return(c(d1, avg_taxrate))
})

res.df <- data.frame(t(res), stringsAsFactors = FALSE)
names(res.df) <- c("county", "property")
res.df
#    county                 property
# 1 anderson Avg. 1.24% of home value
# 2  andrews Avg. 0.88% of home value

这使用了 rvest,提供了一个进度条,并利用了页面上已经存在的 URL:

library(rvest)
library(pbapply)

pg <- read_html("http://www.tax-rates.org/texas/property-tax")

# get all the county tax table links
ctys <- html_nodes(pg, "table.propertyTaxTable > tr > td > a[href*='county_property']")

# match your lowercased names
county_name <- tolower(gsub(" County", "", html_text(ctys)))

# spider each page and return the rate %
county_rate <- pbsapply(html_attr(ctys, "href"), function(URL) {
  cty_pg <- read_html(URL)
  html_text(html_nodes(cty_pg, xpath="//div[@class='box']/div/div[1]/i[1]"))
}, USE.NAMES=FALSE)

tax_table <- data.frame(county_name, county_rate, stringsAsFactors=FALSE)

tax_table
##   county_name              county_rate
## 1    anderson Avg. 1.24% of home value
## 2     andrews Avg. 0.88% of home value
## 3    angelina Avg. 1.35% of home value
## 4     aransas Avg. 1.29% of home value

write.csv(tax_table, "2015_TX_PropertyTaxes.csv")

注意 1:我将抓取限制为 4,以免占用提供免费数据的网站的带宽。

注意 2:该站点上只有 254 个县税链接可用,所以如果你有 255 个,你似乎还有一个额外的链接。

你应该首先初始化一个列表来存储每个循环抓取的数据。确保在进入循环之前对其进行初始化

然后,在每次迭代中,在开始下一次迭代之前追加到列表中。在这里查看我的回答