使用xpath将解析后的html写入R中的文件



我在将解析后的html写入文件时遇到问题。我从xpath指定的表中获得了这些数据,但当我试图将其写入文件时,我会得到"错误在cat(list(…)).

> fileUrl <- "http://www.w3schools.com/html/html_tables.asp"
> library(XML)
> htmlFile <- htmlTreeParse(fileUrl, useInternal = TRUE)
> # and then I grab the table
> urlParse <- xpathSApply(htmlFile, "//table[@class='reference']")
> urlParse[[1]]
[[1]]
<table class="reference" style="width:100%">
  <tr><th>Number</th>&#13;
    <th>First Name</th>&#13;
    <th>Last Name</th>      &#13;
    <th>Points</th>&#13;
</tr>
  <tr><td>1</td>&#13;
    <td>Eve</td>&#13;
    <td>Jackson</td>        &#13;
    <td>94</td>&#13;
</tr>
  <tr><td>2</td>&#13;
    <td>John</td>&#13;
    <td>Doe</td>        &#13;
    <td>80</td>&#13;
</tr>
  <tr><td>3</td>&#13;
    <td>Adam</td>&#13;
    <td>Johnson</td>        &#13;
    <td>67</td>&#13;
</tr>
  <tr><td>4</td>&#13;
    <td>Jill</td>&#13;
    <td>Smith</td>      &#13;
    <td>50</td>&#13;
</tr>
</table> 

这很好,但当我把它写到一个文件中时,我会得到:

> write(urlParse[[1]], file = "file.txt") 
Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'externalptr') cannot be handled by 'cat'

但当我做一些类似的事情时:

> write(c(3234,234,23,4,234), file = "file.txt") 

一切都很好。是因为这是一份清单吗?我尝试了urlParse[1]、toString(urlParse[1])、urlParse\[1]][1]。不知道为什么。

您的XML当前由C级对象表示。您需要将其转换为字符串。saveXML可以用来做这件事:

fileUrl <- "http://www.w3schools.com/html/html_tables.asp"
library(XML)
htmlFile <- htmlTreeParse(fileUrl, useInternal = TRUE)
urlParse <- xpathSApply(htmlFile, "//table[@class='reference']")
myXML <- saveXML(urlParse[[1]])
write(myXML, file = "file.txt")

或简称

saveXML(urlParse[[1]], file = "file.txt")

最新更新