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
相关产品推荐
相关产品推荐

