我在将解析后的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>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr><td>1</td>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr><td>2</td>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr><td>3</td>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
<tr><td>4</td>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</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")