r - R超时中的Web抓取
问题描述
我正在做一个项目,我需要从这个网站下载 FAFSA 完成数据:https ://studentaid.gov/data-center/student/application-volume/fafsa-completion-high-school
我正在使用 rvest 来抓取该数据,但是当我尝试在链接上使用函数 read_html 时,它永远不会读入,最终我不得不停止执行。我可以在其他网站上阅读,所以我不确定这是特定于网站的问题还是我做错了什么。到目前为止,这是我的代码:
library(rvest)
fafsa_link <- "https://studentaid.gov/data-center/student/application-volume/fafsa-completion-high-school"
read_html(fafsa_link)
任何帮助将不胜感激!谢谢!
解决方案
需要用户代理标头。下载链接也在 json 文件中给出。您可以对链接进行正则表达式(或者确实将它们解析出来);或者像我一样,正则表达式,然后替换其中的状态代码以获得额外的下载网址(给定的网址仅在这方面有所不同)
library(magrittr)
library(httr)
library(stringr)
data <- httr::GET('https://studentaid.gov/data-center/student/application-volume/fafsa-completion-high-school.json', add_headers("User-Agent" = "Mozilla/5.0")) %>%
content(as = "text")
ca <- data %>% stringr::str_match(': "(.*?CA\\.xls)"') %>% .[2] %>% paste0('https://studentaid.gov', .)
ma <- gsub('CA\\.xls', 'MA\\.xls' ,ca)
推荐阅读
- css - 如何将绝对元素悬停在相对元素中?
- kotlin - Kotlin 脚本引擎抛出“未解析的引用”,即使包和类是有效的
- mysql - 别名 CASE 语句
- javascript - 如何添加基于时间的弹出成功/失败消息?
- sql - Oracle 根据 Order By 更新前 20 条记录
- asterisk - Asterisk ARI - 在振铃前将通道传递给 Stasis
- matplotlib - mplot3d:在 `plot_surface()` 下隐藏线图`plot()`
- c# - 创建 nuget 包时访问消费者应用程序配置
- scala - 测试 sparksql 查询
- css - 无法定位第二张背景图片