【问题标题】:Google search links obtain by webscraping in R are not in required format在 R 中通过网页抓取获得的 Google 搜索链接不是必需的格式
【发布时间】:2016-08-14 04:13:08
【问题描述】:

我是 R 中网络抓取的新手,并尝试使用 R 中的搜索词运行 google 搜索操作并自动提取链接。我在使用 RCurl 和 XML 包获得谷歌搜索结果的链接方面取得了部分成功。但是,我提取的 href 链接包含不需要的信息,并且不是“URL”格式。

我使用的代码是:

html <- getURL(u)
links <- xpathApply(doc, "//h3//a[@href]", xmlGetAttr, 'href')
links <- grep("http://", links, fixed = TRUE, value=TRUE)

上面的代码给了我七个链接,但是它们的格式如下:

[1] "/url?q=http://theguitarrepairworkshop.com/services/&sa=U&ved=0ahUKEwiOnNXzsr7OAhWHAMAKHX_LApYQFggmMAM&usg=AFQjCNF1r13FMHXXTsxMkbwzortiWKDALQ" 

我希望他们是:

http://theguitarrepairworkshop.com/services/

如何提取上述href?

【问题讨论】:

  • 抓取 google 违反了他们的服务条款。如果您模拟一个不同的抓取示例,我将很乐意提供帮助。
  • RCurl/XML 包使用 Xpath 1.0 还是 Xpath 2.0? 如果它使用 2.0,xpath 语句中的正则表达式函数将提供更简单的代码和更快的性能。
  • @hrbrmstr:谢谢你让我知道。我没有意识到这一点。是否有任何其他合法的替代方法可以通过应用程序从互联网上获取搜索结果。
  • DuckDuckGo 为你提供了 API 但搜索结果不完整duckduckgo.com/api
  • @amrrs:再次感谢。这很有帮助!

标签: r rcurl


【解决方案1】:

使用rvest 包(它也使用XML 包但有很多与抓取相关的方便功能)

library(rvest)
ht <- read_html('https://www.google.co.in/search?q=guitar+repair+workshop')
links <- ht %>% html_nodes(xpath='//h3/a') %>% html_attr('href')
gsub('/url\\?q=','',sapply(strsplit(links[as.vector(grep('url',links))],split='&'),'[',1))

输出:

[1] "http://theguitarrepairworkshop.com/"                                                                   
[2] "http://www.justdial.com/Delhi-NCR/Guitar-Repair-Services/ct-134788"                                    
[3] "http://www.guitarrepairshop.com/"                                                                      
[4] "http://www.guitarworkshoponline.com/"                                                                  
[5] "http://www.guitarrepairbench.com/guitar-building-projects/guitar-workshop/guitar-workshop-project.html"
[6] "http://www.guitarservices.com/"                                                                        
[7] "http://guitarworkshopglasgow.com/pages/repairs-1"                                                      
[8] "http://brightonguitarworkshop.co.uk/"                                                                  
[9] "http://www.luth.org/resources/schools.html"   

代码中的第四行清除了文本。首先拆分结果 url(带有垃圾)wrt '&',然后获取结果拆分的第一个元素并将 '/url?q=' 替换为空。

希望对你有帮助!

【讨论】:

  • 非常感谢您的回复。它解决了这个问题。我正在考虑 strsplit 选项,但是想知道我在获取 href 节点时是否做错了什么。
  • html_nodes(xpath='//h3/a') 此解决方案不再有效。
猜你喜欢
  • 2021-06-12
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 2021-05-03
  • 1970-01-01
相关资源
最近更新 更多