2014-02-15 44 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