【问题标题】:Cleaning Google search results in R在 R 中清理 Google 搜索结果
【发布时间】:2014-08-21 17:53:28
【问题描述】:

R 和抓取、stackoverflow 和 tbh 的全新(就像今天一样)编写任何类型的代码,所以请温柔一点。

我已经设法让搜索返回一个数组(结果),其中包含来自 Google 搜索结果页面的所有 URL:

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 但任何人都可以帮助我使用代码从所有结果中删除所有 gubbins数组?

理想情况下,我应该以......

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

非常感谢。

【问题讨论】:

  • 如果你提供一个最小的工作示例会更容易帮助你:stackoverflow.com/help/mcve
  • 首先,欢迎来到 SO。您提供了一个很好的可重现示例并显示了一些努力,做得很好!最后要做的就是向我们提供您最终想要的结果
  • 希望完成并完成。感谢您的欢迎顺便说一句。

标签: html regex r xpath


【解决方案1】:

不需要多个strsplits或sapply,只需尝试矢量化gsub

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

【讨论】:

  • 完美!杰出的。所以|显然是 OR 语句。这些是否意味着我可以在需要时添加更多语句?
  • 可以,只要它们是有效的正则表达式。看看?regex
  • 酷。会做。再次感谢
【解决方案2】:

或者,你可以

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

【讨论】:

  • (+1) 不错,一如既往。
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多