我需要通过网页浏览一些页面。鉴于页面很多,我首先在外部HD中写下html文件然后处理它们。
问题在于,当我尝试获取URL时,我总是下载相同的页面,因为网站等待半秒钟才能显示新页面。
代码如下
library(RCurl)
library(stringr)
library(XML)
for(i in 1:numberPages){
# Generate the unique URL for each page
url <- str_c('https://www..../#{"page":"', i, '"}')
# Download the page
bill.result <- try(getURL(url))
while(class(bill.result)=="try-error"){ # if class()==error, retry to get the url after 1 sec
cat("Page irresponsive - trying again")
Sys.sleep(1)
bill.result <- try(getURL(url))
}
# Write the page to local hard drive
result <- try(write(bill.result, str_c(new_folder, "/page", i, ".html")))
while(class(result)=="try-error"){ # if class()==error, retry to write after 2 min
cat("I will sleep if network is down")
Sys.sleep(120)
result <- try(write(bill.result, str_c(new_folder, "/page", i, ".html")))
}
# Print progress of download
cat(i, "\n")
}
我已经搜索过,但在获取网址之前,还没有找到等待1秒的选项。没有这个等待时间,我总是下载相同的页面,无论我在循环中的哪个位置。我知道这一点,因为当我在浏览器中更改网址时,页面是相同的1秒钟,然后它会更改为我想要的页面。