如何在给定的持续时间内 运行 一个 R 代码然后停止它?

How to run an R code within a given duration and then stop it?

目前我正在用Rselenium做一个网络爬虫项目,需要依次打开大约100,000个网页并进行信息收集:

url <- paste0("www.111", r0[ii],".com")
remDr$open()
remDr$navigate(url)

这个过程中最耗时的部分似乎是打开一个新网页,尤其是加载广告,外部链接等。所以我怎么能运行这种R代码在特定的时间内(例如,2秒)然后停止,然后运行下面的信息收集过程?谢谢

好的,我的 withTimeout from R.utils 似乎做了你想做的事(延迟后中断一个函数)。

library(R.utils)
A=2
foo <- function() {
while(A>1){print(A)}
}

#foo()#Ridiculous infinite function don't run it

withTimeout(foo(),timeout=0.5)

知道了! R.utils 包确实有效。似乎函数 withTimeout 可以与 try 函数一起使用,以便继续 运行 任何后续函数。例如:

library(RSelenium)  
library(rvest)
library(R.utils)

remDr <- remoteDriver(remoteServerAddr = "127.1.1.1" 
                      , port = 4444
                      , browserName = "firefox") # connect to Server
remDr$open()
try(withTimeout(remDr$navigate("https://aaaa.org"), timeout=0.5)) # stop navigation after 0.5 sec
a1 <- read_html(remDr$getPageSource()[[1]][1])
a2 <- html_nodes(a1, "pre") %>% html_text()

谢谢!