RCurl getURL с циклом - ссылка на PDF убивает цикл
Я долго ломал голову над этим и не могу понять, как это обойти. Проще всего дать рабочий фиктивный код:
require(RCurl)
require(XML)
#set a bunch of options for curl
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
agent="Firefox/23.0"
curl = getCurlHandle()
curlSetOpt(
cookiejar = 'cookies.txt' ,
useragent = agent,
followlocation = TRUE ,
autoreferer = TRUE ,
httpauth = 1L, # "basic" http authorization version -- this seems to make a difference for India servers
curl = curl
)
list1 <- c('http://timesofindia.indiatimes.com//articleshow/2933112.cms',
'http://timesofindia.indiatimes.com//articleshow/2933131.cms',
'http://timesofindia.indiatimes.com//articleshow/2933209.cms',
'http://timesofindia.indiatimes.com//articleshow/2933277.cms')
#note list2 has a new link inserted in 2nd position; this is the link that kills the following getURL calls
list2 <- c('http://timesofindia.indiatimes.com//articleshow/2933112.cms',
'http://timesofindia.indiatimes.com//articleshow/2933019.cms',
'http://timesofindia.indiatimes.com//articleshow/2933131.cms',
'http://timesofindia.indiatimes.com//articleshow/2933209.cms',
'http://timesofindia.indiatimes.com//articleshow/2933277.cms')
for ( i in seq( list1 ) ){
print(list1[i])
html <-
try( getURL(
list1[i],
maxredirs = as.integer(20),
followlocation = TRUE,
curl = curl
),TRUE)
if (class (html) == "try-error") {
print(paste("error accessing",list1[i]))
rm(html)
gc()
next
} else {
print('success')
}
}
gc()
for ( i in seq( list2 ) ){
print(list2[i])
html <-
try( getURL(
list2[i],
maxredirs = as.integer(20),
followlocation = TRUE,
curl = curl
),TRUE)
if (class (html) == "try-error") {
print(paste("error accessing",list2[i]))
rm(html)
gc()
next
} else {
print('success')
}
}
Это должно быть в состоянии работать с установленными библиотеками RCurl и XML. Дело в том, что когда я вставляю http://timesofindia.indiatimes.com//articleshow/2933019.cms
во вторую позицию в списке, это убивает успех остальной части цикла (другие ссылки такие же). Это происходит (в этом и других обстоятельствах последовательно), когда ссылка содержит PDF (проверьте, чтобы увидеть).
Любые мысли о том, как это исправить, чтобы получить ссылку, которая содержит PDF, не убивает мою петлю? Как вы можете видеть, я пытался убрать потенциально оскорбительный объект, gc()
повсюду и т. д., но я не могу понять, почему PDF-файл убивает мою петлю.
Спасибо!
Просто чтобы проверить, вот мой вывод для двух for
петли:
#[1] "http://timesofindia.indiatimes.com//articleshow/2933112.cms"
#[1] "success"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933131.cms"
#[1] "success"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933209.cms"
#[1] "success"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933277.cms"
#[1] "success"
а также
#[1] "http://timesofindia.indiatimes.com//articleshow/2933112.cms"
#[1] "success"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933019.cms"
#[1] "error accessing http://timesofindia.indiatimes.com//articleshow/2933019.cms"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933131.cms"
#[1] "error accessing http://timesofindia.indiatimes.com//articleshow/2933131.cms"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933209.cms"
#[1] "error accessing http://timesofindia.indiatimes.com//articleshow/2933209.cms"
#[1] "http://timesofindia.indiatimes.com//articleshow/2933277.cms"
#[1] "error accessing http://timesofindia.indiatimes.com//articleshow/2933277.cms"
1 ответ
Возможно, вам будет проще использовать httr. Он оборачивает RCurl и устанавливает нужные параметры по умолчанию. Вот эквивалентный код с httr:
require(httr)
urls <- c(
'http://timesofindia.indiatimes.com//articleshow/2933112.cms',
'http://timesofindia.indiatimes.com//articleshow/2933019.cms',
'http://timesofindia.indiatimes.com//articleshow/2933131.cms',
'http://timesofindia.indiatimes.com//articleshow/2933209.cms',
'http://timesofindia.indiatimes.com//articleshow/2933277.cms'
)
responses <- lapply(urls, GET)
sapply(responses, http_status)
sapply(responses, function(x) headers(x)$`content-type`)