使用 rvest 抓取网站数据

Scrape website data using rvest

我正在尝试从以下 link 中抓取对应于 Table 5 的数据:https://www.fbi.gov/about-us/cjis/ucr/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/5tabledatadecpdf/table_5_crime_in_the_united_states_by_state_2013.xls

按照建议,我使用 SelectorGadget 找到相关的 CSS 匹配项,我发现包含所有数据(以及一些无关信息)的匹配项是“#page_content”。 =12=]

我尝试了以下代码,但出现错误:

fbi <- read_html("https://www.fbi.gov/about-us/cjis/ucr/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/5tabledatadecpdf/table_5_crime_in_the_united_states_by_state_2013.xls")

fbi %>%
html_node("#page_content") %>%
html_table()
Error: html_name(x) == "table" is not TRUE

#Try extracting only the first column:
fbi %>%
html_nodes(".group0") %>%
html_table()
Error: html_name(x) == "table" is not TRUE

#Directly feed fbi into html_table
data = fbi %>% html_table(fill = T)
#This output creates a list of 3 elements, where within list 1 and 3, there are many missing values.

如有任何帮助,我们将不胜感激!

您可以直接下载excel文件。之后你应该查看 excel 文件并将你想要的数据放入 csv 文件中。之后,您可以处理数据。下面是执行相同操作的代码。

library(rvest)
library(stringr)
page <- read_html("https://www.fbi.gov/about-us/cjis/ucr/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/5tabledatadecpdf/table_5_crime_in_the_united_states_by_state_2013.xls")


pageAdd <- page %>%
  html_nodes("a") %>%       # find all links
  html_attr("href") %>%     # get the url
  str_subset("\.xls") %>% # find those that end in xls
  .[[1]]     
mydestfile <- "D:/Kumar/table5.xls" # change the path and file name as per your system
download.file(pageAdd, mydestfile, mode="wb")

数据格式不正确。因此在 R 中下载它会更加混乱。对我来说,这似乎是解决您的问题的最佳方法。