我有这个html文件
<html>
<table width="111" >
<tr> <td> A </td>
<td> B </td>
</tr>
<tr> <td> C </td>
<td> D </td>
</tr>
</table>
<table width="222" >
<tr> <td> E </td>
<td> F </td>
</tr>
<tr> <td> G </td>
<td> H </td>
</tr>
</table>
</html>
我在R
正在做
library(XML)
tree = htmlTreeParse(file, useInternal=TRUE, asTree=TRUE)
table = getNodeSet(tree, "//table[@width='222']")[[1]]
xpathSApply(table, "//td", xmlValue)
我正在
[1] " A " " B " " C " " D " " E " " F " " G " " H "
而我却跳来跳去
[1] " E " " F " " G " " H "
我无法理解发生了什么
答案 0 :(得分:1)
就这样做:
# Load libraries
library(XML)
# Load data
base_html <- "<html><table width='111'><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table><table width='222'><tr><td>E</td><td>F</td></tr><tr><td>G</td><td>H</td></tr></table></html>"
# Parse HTML
tree <- htmlTreeParse(base_html, useInternal=TRUE, asTree=TRUE)
# Get data
xpathSApply(tree, "//table[@width='222']/tr/td", xmlValue)
答案 1 :(得分:1)
使用您当前的方法,您可以使用此方法获取值。顺便说一句,您可能不希望将名称table
分配给任何内容,因为它是一个基本的R函数,可能会导致问题。也不需要Rcurl
。
> library(XML)
> doc <- '<html>
<table width="111" >
<tr> <td> A </td>
<td> B </td>
</tr>
<tr> <td> C </td>
<td> D </td>
</tr>
</table>
<table width="222" >
<tr> <td> E </td>
<td> F </td>
</tr>
<tr> <td> G </td>
<td> H </td>
</tr>
</table>
</html>'
> tree <- htmlTreeParse(doc, useInternal = TRUE, asTree = TRUE)
> tab <- getNodeSet(tree, "//table[@ width='222']")[[1]]
> xpathSApply(tab, "//table[@width='222']/tr/td", xmlValue)
[1] " E " " F " " G " " H "
或者,您可以
> tab2 <- getNodeSet(tree, "//table")[[2]]
> xpathSApply(tab2, "//table[@width='222']/tr/td", xmlValue)
[1] " E " " F " " G " " H "