首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >抓取分层数据

抓取分层数据
EN

Stack Overflow用户
提问于 2013-02-02 02:04:06
回答 1查看 338关注 0票数 4

我正在尝试从global Dept stores上抓取大陆/国家的百货商店列表。我运行以下代码首先获取大陆,因为我们可以看到,XML层次结构是这样一种方式,即每个大陆上的国家不是该大陆的子节点。

代码语言:javascript
复制
> 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命令中处理这些国家,但我只是想确保我没有遗漏什么。有没有一种更聪明的方法来一次性获取每个大洲和每个国家的所有数据?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-02 04:18:12

使用xpath,可以使用|分隔符将多个路径组合在一起。所以我用它把商品和商店放在同一个列表中。然后我得到了第二个内容列表。我使用后一个列表来拆分第一个列表

代码语言:javascript
复制
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。

代码语言:javascript
复制
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)

我可以检查结果:

代码语言:javascript
复制
> 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"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14652362

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档