如何用R语言构建带年份参数的URL生成函数read_url?
实现通用年份维基百科URL生成函数
read_url 函数功能
该函数接收一个年份参数,生成对应年份的维基百科页面URL。核心的URL拼接逻辑无需依赖rvest包,若后续需爬取页面内容,再结合rvest扩展即可。
函数实现代码
read_url <- function(year) { # 可选参数校验:确保输入为有效年份 if (!is.numeric(year) || year < 1 || year > as.integer(format(Sys.Date(), "%Y"))) { stop("请输入有效的年份数值") } # 拼接维基百科基础URL与年份参数 base_url <- "https://en.wikipedia.org/wiki/" paste0(base_url, as.integer(year)) }
使用示例
- 调用
read_url(2020),将返回:https://en.wikipedia.org/wiki/2020 - 调用
read_url(2015),将返回:https://en.wikipedia.org/wiki/2015
结合rvest的扩展用法(可选)
如果需要爬取生成URL对应的页面内容,可基于该函数扩展:
library(rvest) # 获取年份页面的标题 get_year_page_title <- function(year) { target_url <- read_url(year) target_url %>% read_html() %>% html_element("h1") %>% html_text() } # 示例:获取2020年维基百科页面标题 get_year_page_title(2020)
内容的提问来源于stack exchange,提问作者Sara Dwindler
相关产品推荐
相关产品推荐

