質問

I have this html file

<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>

And in R I am doing

library(XML)
tree = htmlTreeParse(file, useInternal=TRUE, asTree=TRUE)
table = getNodeSet(tree, "//table[@width='222']")[[1]]
xpathSApply(table, "//td", xmlValue)

And I'm getting

[1] " A " " B " " C " " D " " E " " F " " G " " H "

whereas I was hopping to get

[1]  " E " " F " " G " " H "

I can't understand what's going on

役に立ちましたか?

解決

Just do it like that:

# 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)

他のヒント

Using your current method, you can get the values with this. By the way, you may not want to assign the name table to anything, as it's a base R function and might cause trouble down the line. No need for Rcurl either.

> 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 "

Alternatively, you could do

> tab2 <- getNodeSet(tree, "//table")[[2]]
> xpathSApply(tab2, "//table[@width='222']/tr/td", xmlValue)
[1] " E " " F " " G " " H "
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top