使用R和XML
包,我一直在試圖從有類似這樣的結構HTML文件地址:如何解析一個嵌套結構的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
屬於哪個值?
非常感謝你。它確實似乎''''去根。這也適用:'xpathSApply(divs [[1]],「span [@ class ='name']」,xmlValue)'。我意識到你可以使用'node'和'/ node'來搜索節點,但不知道'node'也可以。 – Stibu