2015-10-19 73 views
0

我正試圖在R中學習網絡抓取,並試圖從以下鏈接List of Cuisines on Wiki的各種表格中抓取數據。在頁面底部有幾張桌子,列出不同種類的美食,我想單獨閱讀。我嘗試使用CSS選擇器,但我認爲我使用他們錯了,這裏是我的代碼片段:使用R擷取網站中表格的數據

require(rvest) 
require(magrittr) 
connection = html_session("https://en.wikipedia.org/wiki/List_of_cuisines") 
connection %>% html_nodes("table:nth-child(1) a") %>% html_text() 
#This lists down all the links in every table there is on that website 
#I also tried connection %>% html_nodes("table:nth-child(2) a") %>% html_text() 
#which gave a different list altogether 

我試圖產生輸出應該是這樣的

  1. 美食
    • 名單所有菜系
  2. 非洲美食
    • 名單非洲美食

等上,這個名單是從HTML表格填充的。

我真的很感激一些指導。謝謝。

回答

1

這使用XPath並獲取所有單個鏈接。我這樣做是爲了展示如何用XPath做「鬆散」的兒童定位(你也可以用CSS選擇器做一定程度的)。希望足夠的食物讓你思考做你想做的事情。基本上你可以分成兩個步驟,一個獲得單獨的表格,然後另一個獲得下面的鏈接:

library(xml2) 
library(rvest) 

pg <- html_session("https://en.wikipedia.org/wiki/List_of_cuisines") 

links <- html_nodes(pg, xpath="//table[contains(@class, 'navbox')]// 
            table[contains(@class, 'nowraplinks')]// 
            td[contains(@class, 'navbox-list')]// 
            li/a") 

length(links) 
## [1] 1005 

head(html_attr(links, "href"), 20) 
## [1] "/wiki/African_cuisine"     
## [2] "/wiki/North_African_cuisine"   
## [3] "/wiki/West_African_cuisine"    
## [4] "/wiki/List_of_African_cuisines"   
## [5] "/wiki/Cuisine_of_the_Americas"   
## [6] "/wiki/North_American_cuisine"   
## [7] "/wiki/South_American_cuisine"   
## [8] "/wiki/List_of_cuisines_of_the_Americas" 
## [9] "/wiki/Asian_cuisine"     
## [10] "/wiki/Central_Asian_cuisine"   
## [11] "/wiki/South_Asian_cuisine"    
## [12] "/wiki/List_of_Asian_cuisines"   
## [13] "/wiki/Balkan_cuisine"     
## [14] "/wiki/Bengali_cuisine"     
## [15] "/wiki/Caribbean_cuisine"    
## [16] "/wiki/Caucasian_cuisine"    
## [17] "/wiki/European_cuisine"     
## [18] "/wiki/Central_European_cuisine"   
## [19] "/wiki/Eastern_European_cuisine"   
## [20] "/wiki/List_of_European_cuisines" 
+0

我正在尋找類似的東西,它確實有幫助。 @hrbrmstr XPath當然似乎是一種更好的方法。 –