2014-02-15 47 views
2

提取文本的HTML我需要提取文本的从在R包XML如何,使用R

使用

require(XML) 
    require(RCurl) 
input<-"R%statistical%Software" 
require(XML) 
    require(RCurl) 
    url <- paste("https://www.google.com/search?q=\"", 
       input, "\"", sep = "") 

    CAINFO = paste(system.file(package="RCurl"), "/CurlSSL/ca-bundle.crt", sep = "") 
    script <- getURL(url, followlocation = TRUE, cainfo = CAINFO) 
    doc <- htmlParse(script) 

所提取的HTML的提取物获得的一组谷歌结果的块的以下文件如下

</ul></div> 
</div> 
</div> 
<span class="st">R, also called GNU S, is a strongly functional language and environment to <br> 
statistically explore data sets, make many graphical displays of data from custom<br> 
 <b>...</b></span><br> 
</div> 
<table class="slk" cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin-top:1px"> 
<tr class="mslg"> 
<td style="padding-left:23px;vertical-align:top"><div class="sld"> 

在这个例子中,我需要提取每个结果下面的文本返回

“R,也被称为GNU S,是一种强烈的函数式语言和环境
统计研究数据集,使数据的很多图形显示从定制

我曾与一些功能于一身去R的XML包,但我不认为我对HTML和XML有足够的了解。 文本将每个结果返回而变化,所以它实际上是

<span class="st"> 

?场?我需要提取。 正如您可能已经猜到,我不熟悉HTML或XML。因此,对于能够给我足够的概述来解决这些问题的好教程或书籍的任何建议将是非常受欢迎的。 谢谢

+0

你可以发布一个链接到你正在解析的文件吗? – jlhoward

回答

4

这将使用class="st"(文档中有7)返回一个列表,result与来自所有span标签的文本。

input<-"R%statistical%Software" 
url <- paste0("http://www.google.com/search?q=",input) 
doc <- htmlParse(url) 
result <- lapply(doc['//span[@class="st"]'],xmlValue) 
result[1] 
# [[1]] 
# [1] "R, also called GNU S, is a strongly functional language and environment to \nstatistically explore data sets, make many graphical displays of data from custom\n ..." 

注意使用http而不是https大大简化了文档的检索。

+0

神奇,它的工作原理,谢谢 – AndyC