全新 R ,所以我会尽力解释这一点。 我一直在使用" rvest"进行数据抓取。包。在这个例子中,我从维基百科的表格中搜集美国州人口。我使用的代码是:
library(rvest)
statepop = read_html("https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population")
forecasthtml = html_nodes(statepop, "td")
forecasttext = html_text(forecasthtml)
forecasttext
结果输出如下:
[2] "7000100000000000000♠1"
[3] " California"
[4] "39,250,017"
[5] "37,254,503"
[6] "7001530000000000000♠53"
[7] "738,581"
[8] "702,905"
[9] "12.15%"
[10] "7000200000000000000♠2"
[11] "7000200000000000000♠2"
[12] " Texas"
[13] "27,862,596"
[14] "25,146,105"
[15] "7001360000000000000♠36"
[16] "763,031"
[17] "698,487"
[18] "8.62%"
如何将这些文本字符串转换为与原始维基百科页面(包含列,行等)的显示方式类似的表格?
答案 0 :(得分:2)
尝试使用rvest的html_table函数 请注意,页面上有五个表,因此您需要指定要解析的表。
library(rvest)
statepop = read_html("https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population")
#find all of the tables on the page
tables<-html_nodes(statepop, "table")
#convert the first table into a dataframe
table1<-html_table(tables[1])