2017-02-17 53 views
0

品牌全新为R,所以我会尽我所能解释这一点。 我一直在玩使用“rvest”软件包进行数据抓取。在这个例子中,我从维基百科的桌子上刮掉了美国的州人口。我使用的代码是:如何将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%" 

我怎么能拒绝文本的这些字符串放到设置类似于它呈现的方式表原始维基百科页面(包括列,行等)?

+1

使用'html_table()'而不是'html_text()' – Nate

回答

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])