在R中清理Google搜索结果

时间:2014-08-21 17:53:28

标签: html regex r xpath

全新(像今天这样)R和scraping,stackoverflow和tbh编写任何类型的代码所以请温柔。

我设法通过Google搜索结果页面的所有网址进行搜索以返回数组(结果):

require(XML)
require(stringr)
xPath <- "//h3//a[@href]"

html <- getURL("http://google.com/search?q=site%3AneatlyformedpartofURL.com+somekeyword")   # read in page contents
doc <- htmlParse(html)    # parse HTML into tree structure
nodes <- xpathApply(doc, xPath, xmlAttrs)   # extract url nodes using XPath. 
results <- sapply(nodes, function(x) x[[1]])    # extract urls
free(doc)   # free doc from memory
results

[1] "/url?q=http://www.neatlyformedpartofURL.com/some-page-ref1/&sa=U&ei=iSr2U-KhA4LH7AaLy4Ao&ved=0CBQQFjAA&usg=AFQjCNFTW0cOKDsALw_3I8g7e-q_6kTJ6g"      
[2] "/url?q=http://www.neatlyformedpartofURL.com/some-page-ref2/&sa=U&ei=iSr2U-KhA4LH7AaLy4Ao&ved=0CBsQFjAB&usg=AFQjCNHtz7hGnkBlApSYLFgRr_baSTWldw"

但是每个结果在实际URL之前和之后都有垃圾。我还设法使用;

去除所有的gubbins
l1 <- unlist(strsplit(results, split='?q=', fixed=TRUE))[2] # strip everything before the http:// 
l2 <- unlist(strsplit(l1[2], split='/&sa', fixed=TRUE))[1]  # strip everything added by google after the url

将返回:

[1] http://www.neatlyformedpartofURL.com/some-page-ref1

但是那就是它。它看起来像unlist(strsplit ...只是对结果数组的第一个结果进行操作。我怀疑它可能涉及sapply但是任何人都可以帮助我使用代码去除所有结果中的所有结果阵列

理想情况下,我最终应该......

   [1] http://www.neatlyformedpartofURL.com/some-page-ref1
   [2] http://www.neatlyformedpartofURL.com/some-page-ref2

非常感谢。

2 个答案:

答案 0 :(得分:2)

无需多个strsplitsapply,只需尝试向量化gsub

gsub("(/url[?]q=)|(/&sa.*)", "", results)
## [1] "http://www.neatlyformedpartofURL.com/some-page-ref1"
## [2] "http://www.neatlyformedpartofURL.com/some-page-ref2"

答案 1 :(得分:1)

或者,你可以

 library(stringr)
 str_extract(results, perl('(?<=\\=).*(?=\\/)'))
 #[1] "http://www.neatlyformedpartofURL.com/some-page-ref1"
 #[2] "http://www.neatlyformedpartofURL.com/some-page-ref2"