xml – 使用并行化来用R抓取网页
发布时间:2020-12-16 07:45:52 所属栏目:百科 来源:网络整理
导读:我试图刮掉大量的网页,以便以后分析它们.由于URL的数量巨大,我决定使用并行包和 XML. 具体来说,我正在使用XML中的htmlParse()函数,它在与sapply一起使用时工作正常,但在与parSapply一起使用时会生成类HTMLInternalDocument的空对象. url1- "http://forums.ph
|
我试图刮掉大量的网页,以便以后分析它们.由于URL的数量巨大,我决定使用并行包和
XML.
具体来说,我正在使用XML中的htmlParse()函数,它在与sapply一起使用时工作正常,但在与parSapply一起使用时会生成类HTMLInternalDocument的空对象. url1<- "http://forums.philosophyforums.com/threads/senses-of-truth-63636.html"
url2<- "http://forums.philosophyforums.com/threads/the-limits-of-my-language-impossibly-mean-the-limits-of-my-world-62183.html"
url3<- "http://forums.philosophyforums.com/threads/how-language-models-reality-63487.html"
myFunction<- function(x){
cl<- makeCluster(getOption("cl.cores",detectCores()))
ok<- parSapply(cl=cl,X=x,FUN=htmlParse)
return(ok)
}
urls<- c(url1,url2,url3)
#Works
output1<- sapply(urls,function(x)htmlParse(x))
str(output1[[1]])
> Classes 'HTMLInternalDocument','HTMLInternalDocument','XMLInternalDocument','XMLAbstractDocument','oldClass' <externalptr>
output1[[1]]
#Doesn't work
myFunction<- function(x){
cl<- makeCluster(getOption("cl.cores",FUN=htmlParse)
stopCluster(cl)
return(ok)
}
output2<- myFunction(urls)
str(output2[[1]])
> Classes 'HTMLInternalDocument','oldClass' <externalptr>
output2[[1]]
#empty
谢谢.
您可以使用Rcurl包中的getURIAsynchronous,允许调用者指定多个URI同时下载.
library(RCurl)
library(XML)
get.asynch <- function(urls){
txt <- getURIAsynchronous(urls)
## this part can be easily parallelized
## I am juste using lapply here as first attempt
res <- lapply(txt,function(x){
doc <- htmlParse(x,asText=TRUE)
xpathSApply(doc,"/html/body/h2[2]",xmlValue)
})
}
get.synch <- function(urls){
lapply(urls,function(x){
doc <- htmlParse(x)
res2 <- xpathSApply(doc,xmlValue)
res2
})}
这里有一些100 url的基准测试,你将解析时间除以2倍. library(microbenchmark)
uris = c("http://www.omegahat.org/RCurl/index.html")
urls <- replicate(100,uris)
microbenchmark(get.asynch(urls),get.synch(urls),times=1)
Unit: seconds
expr min lq median uq max neval
get.asynch(urls) 22.53783 22.53783 22.53783 22.53783 22.53783 1
get.synch(urls) 39.50615 39.50615 39.50615 39.50615 39.50615 1
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Oracle12.2 RAC集群管理之增加删除节点_Oracle12cR2视频教程
- c# – 如何基于多列对DataTable进行排序?
- ms-access – Visual Basic 6数据结构
- zTree保持展开单一路径之简易实现
- react-native组件与React.createClass的优点和缺点是实现UI
- c# – 允许服务与Windows中的桌面交互
- c – 有没有办法在不重建任何项目的情况下重新链接解决方案
- 使用RSL发布flex项目需要的build.xml要诀详解 – IT妖
- ruby-on-rails – rspec控制器测试,预期响应为a,但是
- ruby-on-rails – 在Ruby On Rails上使用PhantomJS进行动态
