首页 > 解决方案 > 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)

任何帮助将不胜感激!谢谢!

标签: rweb-scrapingrvest

解决方案


需要用户代理标头。下载链接也在 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)

推荐阅读