0

这是带有循环的 RCurl getURL 的后续问题 - 链接到 PDF 会杀死循环

我有以下getURL命令:

require(RCurl)
#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
)


x = getURLContent('http://timesofindia.indiatimes.com//articleshow/2933019.cms')
class(x)
#[1] "character"
attr(x, "Content-Type")
#"text/plain" 

在浏览器中,上面的链接最终会重定向到:

x = getURLContent('http://timesofindia.indiatimes.com/photo.cms?msid=2933009')
class(x)
#[1] "raw"
attr(x, "Content-Type")
#"application/pdf" 

假设我只知道第一个链接,我如何检测重定向(或重定向)的最终位置是某种类型(在本例中为 PDF)?

谢谢!!

4

2 回答 2

1

我遇到了类似的问题,尝试使用摘要身份验证运行 getURLContent 以获取二进制数据(使用非标准 mime 类型)。我在 R 2.15.3 上运行 RCurl v1.95-4.1。

如果我在没有 binary=TRUE 标志的情况下运行 getURLContent,它不会自动切换到 binary=TRUE,因为此数据类型的 mime 标头,因此它会尝试执行 rawToChar() 并抛出“字符串中嵌入的 NULL”错误。但是,身份验证确实有效。

如果我在 getURLContent 调用中添加 binary=TRUE 标志,这似乎会导致身份验证步骤出现问题,因为我随后会收到“错误:未经授权”响应。

最终起作用的是用 getBinaryURL() [如上例] 替换 getURLContent(),这允许 userpwd="u:p" 授权工作并将二进制数据传递给我分配的对象。

我认为 RCurl 的作者根据我在 GitHub 中看到的内容,对 getURLContent 对 v1.97 二进制数据的处理进行了改进,因此这可能已成为过去……除了我们这些仍在运行旧 R 的人设置。

于 2014-10-29T19:37:22.420 回答
1

也许有更好的解决方案,但一种方法可能是:

# ...
h <- basicTextGatherer()
x = getBinaryURL('http://timesofindia.indiatimes.com//articleshow/2933019.cms', 
                 headerfunction = h$update, curl = curl)
r <- gregexpr("Content-Type:.*?\n", h$value())
tail(regmatches(h$value(), r)[[1]], 1)
# [1] "Content-Type: application/pdf\r\n"   
于 2014-08-24T18:16:23.447 回答