【发布时间】:2016-12-27 03:12:46
【问题描述】:
使用 R 和 XML 包,我一直在尝试从结构类似于以下的 html 文件中提取地址:
<!DOCTYPE html>
<body>
<div class='entry'>
<span class='name'>Marcus Smith</span>
<span class='town'>New York</span>
<span class='phone'>123456789</span>
</div>
<div class='entry'>
<span class='name'>Henry Higgins</span>
<span class='town'>London</span>
</div>
<div class='entry'>
<span class='name'>Paul Miller</span>
<span class='town'>Boston</span>
<span class='phone'>987654321</span>
</div>
</body>
</html>
我先做以下事情
library(XML)
html <- htmlTreeParse("test.html", useInternalNodes = TRUE)
root <- xmlRoot(html)
现在,我可以用这个得到所有的名字:
xpathSApply(root, "//span[@class='name']", xmlValue)
## [1] "Marcus Smith" "Henry Higgins" "Paul Miller"
现在的问题是某些元素并不存在于所有地址中。在示例中,这是电话号码:
xpathSApply(root, "//span[@class='phone']", xmlValue)
## [1] "123456789" "987654321"
如果我这样做,我就无法将电话号码分配给正确的人。所以,我尝试先将整个通讯录条目提取如下:
divs <- getNodeSet(root, "//div[@class='entry']")
divs[[1]]
## <div class="entry">
## <span class="name">Marcus Smith</span>
## <span class="town">New York</span>
## <span class="phone">123456789</span>
## </div>
从输出我想我已经达到了我的目标,我可以得到,例如,对应于第一个条目的名称如下:
xpathSApply(divs[[1]], "//span[@class='name']", xmlValue)
## [1] "Marcus Smith" "Henry Higgins" "Paul Miller"
但即使divs[[1]] 的输出只显示了Marcus Smith 的数据,我还是得到了所有三个名字。
这是为什么?我该怎么做才能以这样的方式提取地址数据,我知道name、town 和phone 的哪些值属于一起?
【问题讨论】:
标签: html r html-parsing