You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言PokemonDB爬虫函数:变量与URL拼接报错问题

解决R函数爬取宝可梦升级技能表的参数问题

错误根源

你调用move_list(donphan)时,R会把donphan当作一个已定义的对象去查找,但你实际想传入的是字符串"donphan",这就是报错"object 'donphan' not found"的核心原因。

两种解决方案

方案1:强制传入字符串(简单直接)

定义函数时接收字符串参数,调用时给宝可梦名称加引号即可:

# 先加载网页爬取所需的包
library(rvest)

move_list <- function(pokemon_name) {
  # 拼接PokemonDB升级技能表的目标URL
  url <- paste0("https://pokemondb.net/pokedex/", pokemon_name, "/moves/level-up")
  
  # 爬取页面并提取升级技能表数据
  page <- read_html(url)
  moves_table <- page %>% 
    html_element("table#moves-levelup") %>% 
    html_table(header = TRUE)
  
  return(moves_table)
}

# 正确调用方式(必须加引号)
move_list("donphan")

方案2:支持无引号输入(更便捷)

通过deparse(substitute())把传入的符号转换为字符串,这样就能直接写move_list(donphan):

library(rvest)

move_list <- function(pokemon_name) {
  # 将符号形式的参数转为字符串
  pokemon_str <- deparse(substitute(pokemon_name))
  url <- paste0("https://pokemondb.net/pokedex/", pokemon_str, "/moves/level-up")
  
  page <- read_html(url)
  moves_table <- page %>% 
    html_element("table#moves-levelup") %>% 
    html_table(header = TRUE)
  
  return(moves_table)
}

# 调用示例(无需加引号)
move_list(donphan)

注意事项

  • 宝可梦名称必须和PokemonDB网站上的完全一致,比如带连字符的mr-mime、大小写正确的Pikachu,否则会出现页面不存在、无法爬取数据的问题。
  • 确保已安装并加载rvest包,这是实现网页爬取和解析的基础工具。

内容的提问来源于stack exchange,提问作者NaturalLite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:20:46