R:检查url的存在,httr:GET()和url.exists()的问题

Ada*_*dam 12 html url get r httr

我有一个大约13,000个URL的列表,我想从中提取信息,但是,并非每个URL实际存在.事实上,大多数人没有.我刚尝试通过所有13,000个网址,html()但需要很长时间.我试图找出如何在解析它们之前查看url是否实际存在html().我已经尝试使用httrGET()功能,以及rcurlsurl.exists()功能.由于某种原因,即使URL确实存在,也url.exist()始终返回FALSE值,并且我使用的方式GET()总是返回成功,我认为这是因为页面被重定向.

以下URL表示我正在解析的页面类型,第一个不存在

urls <- data.frame('site' = 1:3, 'urls' = c('https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-1&unit=SLE010', 
                            'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=HMM202',
                            'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=SLE339'))

urls$urls <- as.character(urls$urls)
Run Code Online (Sandbox Code Playgroud)

因为GET(),问题是第二个URL实际上并不存在,但它被重定向,因此返回"成功".

 urls$urlExists <- sapply(1:length(urls[,1]), 
                     function(x) ifelse(http_status(GET(urls[x, 'urls']))[[1]] == "success", 1, 0))
Run Code Online (Sandbox Code Playgroud)

因为url.exists(),即使第一个和第三个URL确实存在,我也会返回三个FALSE.

 urls$urlExists2 <- sapply(1:length(urls[,1]), function(x) url.exists(urls[x, 'urls']))
Run Code Online (Sandbox Code Playgroud)

我查了一下这两个职位1,2,但我宁愿不使用的用户代理,只是因为我不知道如何找到我的,或者它是否会使用其他计算机上的验证码不同人的变化.因此,使代码更难以被其他人接收和使用.两篇帖子的答案建议使用GET()in httr.这似乎GET()是首选的方法,但我需要弄清楚如何处理重定向问题.

在解析它们之前,任何人都可以建议在R中测试URL的存在html()吗?我也很乐意为此问题提出任何其他建议的工作.

更新:

在查看了返回的值后,GET()我想出了一个解决方法,详细了解答案.

had*_*ley 19

使用httr,url_success()关闭后使用和重定向:

library(httr)

urls <- c(
  'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-1&unit=SLE010', 
  'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=HMM202',
  'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=SLE339'
)

sapply(urls, url_success, config(followlocation = 0L), USE.NAMES = FALSE)
Run Code Online (Sandbox Code Playgroud)

  • 因为我遇到了同样的问题所以只留下一张纸条.使用当前版本(1.2.1),我们使用`http_error`而不是`url_success`. (5认同)

Shi*_*ang 5

url_success(x)已弃用;请改用!http_error(x)

所以更新hadley的解决方案。

> library(httr)
> 
> urls <- c(  
> 'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-1&unit=SLE010',
> 'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=HMM202',
> 'https://www.deakin.edu.au/current-students/unitguides/UnitGuide.php?year=2015&semester=TRI-2&unit=SLE339'
> )
> 
> !sapply(urls, http_error)
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 2

在 @TimBiegeleisen 的建议之后,我查看了 function 返回的内容GET()。看起来,如果 url 存在,GET()则会返回该 url 作为值,但如果重定向,则会返回不同的 url。我只是更改了代码,看看返回的 url 是否与GET()我提交的匹配。

urls$urlExists <- sapply(1:length(urls[,1]), function(x) ifelse(GET(urls[x, 'urls'])[[1]] == urls[x,'urls'], 1, 0))
Run Code Online (Sandbox Code Playgroud)

我有兴趣了解人们用于同一件事的任何更好的方法。