2015-09-02 53 views
3

我在按照this question選擇的答案時遇到問題。我試圖抓取的表格是this list of U.S. state populations維基百科故障刮表

library(XML) 
theurl <- "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population" 
tables <- readHTMLTable(theurl) 
n.rows <- unlist(lapply(tables, function(t) dim(t)[1])) 

這是我得到的錯誤..

Error: failed to load external entity "http://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population" 

是怎麼回事?

(注 - 雖然我在尋找解決這個錯誤,如果你可以點我得到的人口數據我會很感激的更簡單的方法)

+0

Wikipedia允許免費下載他們的整個數據庫... https://en.wikipedia.org/wiki/Wikipedia:Database_download這應該會減少已經超出網絡服務器 – ScottMcGready

+4

err,你可以按照參考鏈接對於有問題的數據,可在頁面底部找到,然後轉到[參考站點](http://www.census.gov/popest/data/state/totals/2013/index.html),也稱爲作爲人口普查,並下載其中包含的csv或xls。 –

+1

@ScottMcGready,你必須有一個大的外部HD。 :)這不是一個小的下載,你只是在那裏提供一個50行的表格,其中包含一些感興趣的列。 –

回答

2

沒有什麼不對您的代碼。但是,您的網址存在問題。

您可以通過一個殼,並試圖驗證外部輸入到你的代碼不會導致它失敗,例如測試,

curl https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population 

將空體,類似於返回到您的R代碼。這應該導致你相信這不是你的R代碼有問題。在作出這一發現,你可能會繼續在其中您有興趣,再使用捲曲你的自由和簡單的測試環境的頁面的部分,並運行

curl https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_population#States_and_territories 

這肯定會不返回空的結果:

... 
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-List_of_U_S_states_and_territories_by_population skin-vector action-view"> 
    <div id="mw-page-base" class="noprint"></div> 
    <div id="mw-head-base" class="noprint"></div> 
    <div id="content" class="mw-body" role="main"> 
1

這是很容易在rvest

library(rvest); library(magrittr) # for %>% 

theurl %>% 
    html() %>% 
    html_nodes("table") %>% extract(1) %>% 
    html_table(fill=TRUE) %>% extract(1) -> pop_table 

見@科裏的blog更多的信息做。