You need to enable JavaScript to run this app. R语言rvest用lapply爬取多页时报xml_find_all错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

R语言rvest用lapply爬取多页时报xml_find_all错误如何解决

问题原因
  • 你通过lapply(read_html)得到的bun是包含多个单页HTML解析对象的列表,而rvest的html_nodes仅支持接收单个HTML对象作为输入,直接对列表调用该方法就会触发你遇到的类匹配报错。
  • 你生成多页URL的逻辑存在格式错误:原始URL已经携带查询参数,再拼接?page=会导致URL参数冲突,请求不到正确的页面内容。
修复后完整代码
library(rvest)
library(stringr)

# 基础URL,移除末尾自带的page参数避免冲突
base_url <- 'https://www.bunnings.com.au/products/bathroom-plumbing/plumbing/pipe-fittings/push-fit-pipe-fittings?L0=products&L1=bathroom-plumbing&L2=plumbing&L3=pipe-fittings&L4=push-fit-pipe-fittings&pageSize=36'

get_last_page <- function(html){
  pages_data <- html %>% 
    html_nodes('.MuiPaginationItem-sizeLarge') %>% 
    html_text()                  
  
  pages_data[(length(pages_data)-1)] %>% 
    unname() %>% 
    as.numeric() 
}

first_page <- read_html(base_url)
latest_page_number <- get_last_page(first_page)

# 正确拼接多页参数
list_of_pages <- str_c(base_url, '&page=', 1:latest_page_number)

# 封装单页数据提取函数
get_page_data <- function(page_html) {
  data.frame(
    paint = page_html %>% html_nodes(".product-title") %>% html_text(), 
    price = page_html %>% html_nodes(".price-medium-size p") %>% html_text(),
    stringsAsFactors = FALSE
  )
}

# 批量提取+合并所有页面数据
all_data <- list_of_pages %>%
  lapply(read_html) %>%
  lapply(get_page_data) %>%
  do.call(rbind, .)
核心修改点
  • 调整了基础URL,移除了自带的page=1参数,拼接多页地址时使用&page=符合URL参数规范
  • 封装了单页数据提取函数get_page_data,用lapply遍历每个页面的HTML对象分别提取数据
  • 用do.call(rbind, .)把所有页面提取到的子数据框按行合并为一个完整数据框,最终结果保存在all_data中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 10:45:04