RCurl getURLContent通过最终重定向检测内容类型 [英] RCurl getURLContent detect content type through final redirect

查看:129
本文介绍了RCurl getURLContent通过最终重定向检测内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对 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" 

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

In a browser, the link above ends up redirecting to:

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

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

Assuming I know only the first link, how can I detect that the final location of the redirect (or redirects) is of a certain type (in this case PDF)?

谢谢!

推荐答案

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

Maybe there's a better solution, but one way could be this:

# ...
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"   

这篇关于RCurl getURLContent通过最终重定向检测内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆