2013-02-01 3 views
4

대륙/국가에 대한 Dept 상점 목록을 global Dept stores에서 긁어 내려고했습니다. 각 대륙을 가진 국가가 그 대륙의 자식 노드가 아닌 XML 계층 구조를 볼 수 있기 때문에 대륙을 먼저 얻으려면 다음 코드를 실행하고 있습니다.계층 적 데이터 스크랩

> url<-"http://en.wikipedia.org/wiki/List_of_department_stores_by_country" 
> doc = htmlTreeParse(url, useInternalNodes = T) 
> nodeNames = getNodeSet(doc, "//h2/span[@class='mw-headline']") 
> # For Africa 
> xmlChildren(nodeNames[[1]]) 
$a 
<a href="/wiki/Africa" title="Africa">Africa</a> 

attr(,"class") 
[1] "XMLInternalNodeList" "XMLNodeList"   
> xmlSize(nodeNames[[1]]) 
[1] 1 

은 내가 별도의 getNodeSet 명령에 국가를 할 수있는 알고 있지만 난 그냥 모르는 뭔가가 있지 않다 있는지 확인하고 싶었다. 각 대륙 내의 모든 데이터를 한꺼번에 가져 오는 더 똑똑한 방법이 있습니까?

+0

문서의 구조를 감안할 때, SAX 함께 구문 분석보다는 DOM 트리를 사용하는 것이 더 쉬울 수 있습니다. – juba

답변

1

uisng xpath, 여러 경로를 | 분리 기호. 그래서 나는 같은 목록에있는 콘테스트와 상점을 얻기 위해 그것을 사용합니다. 그럼 두 번째 목록을 얻습니다. 나중 목록을 사용하여 첫 번째 항목을 분할합니다.

url<-"http://en.wikipedia.org/wiki/List_of_department_stores_by_country" 
library(XML) 
xmltext <- htmlTreeParse(url, useInternalNodes = T) 

## Here I use the combined xpath 
cont.shops <- xpathApply(xmltext, '//*[@id="mw-content-text"]/ul/li| 
            //*[@id="mw-content-text"]/h3',xmlValue) 
cont.shops<- do.call(rbind,cont.shops)     ## from list to vector 


head(cont.shops)     ## first element is country followed by shops 
    [,1]     
[1,] "[edit] Â Tunisia"  
[2,] "Magasin Général" 
[3,] "Mercure Market"  
[4,] "Promogro"    
[5,] "Geant"     
[6,] "Carrefour"    
## I get all the contries in one list 
contries <- xpathApply(xmltext, '//*[@id="mw-content-text"]/h3',xmlValue) 
contries <- do.call(rbind,contries)      ## from list to vector 

    head(contries) 
    [,1]     
[1,] "[edit] Â Tunisia"  
[2,] "[edit] Â Morocco"  
[3,] "[edit] Â Ghana"  
[4,] "[edit] Â Kenya"  
[5,] "[edit] Â Nigeria"  
[6,] "[edit] Â South Africa" 

이제 국가를 사용하여 cont.shops를 분할하는 처리를 수행합니다.

dd <- which(cont.shops %in% contries)     ## get the index of contries 
freq <- c(diff(dd),length(cont.shops)-tail(dd,1)+1)  ## use diff to get Frequencies 
contries.f <- rep(contries,freq)      ## create the factor splitter 


ll <- split(cont.shops,contries.f) 

나는 결과를 확인할 수 있습니다

> ll[[contries[1]]] 
[1] "[edit]  Tunisia"  "Magasin Général" "Mercure Market"  "Promogro"    "Geant"     
[6] "Carrefour"    "Monoprix"    
> ll[[contries[2]]] 
[1] "[edit] Â Morocco"               
[2] "Alpha 55, one 6-story store in Casablanca"         
[3] "Galeries Lafayette, to open in 2011[1] within Morocco Mall, in Casablanca" 
+0

매우 도움이되었습니다. 고맙습니다 – user1848018