使用rvest爬取时如何将长度不同的标题和段落提取为不同列
存在的两个核心问题
- 目标URL填写错误:你代码中使用的是宪法列表页地址,而非你需要爬取的古巴2018宪法详情页地址,导致提取的内容本身不符合预期
- 数据合并逻辑错误:章节标题和段落是一对多的层级关系,两者长度天然不一致,不能直接按列合并,需要先按层级归属匹配每段内容对应的章节标题
修正后可运行代码
pacman::p_load(tidyverse, rvest) # 填写正确的目标宪法页面地址 url <- "https://www.constituteproject.org/constitution/Cuba_2018D?lang=es" page <- read_html(url) # 提取所有章节标题节点 titulo_nodes <- html_nodes(page, ".float-left") # 遍历每个标题节点,匹配其下属的所有段落 final <- map_dfr(seq_along(titulo_nodes), function(i) { # 提取当前章节标题 titulo_actual <- html_text(titulo_nodes[i]) # 定位当前章节之后、下一章之前的所有p标签内容 if (i < length(titulo_nodes)) { paras <- html_nodes(titulo_nodes[i], xpath = "following-sibling::p[following-sibling::*[contains(@class, 'float-left')][1]]") %>% html_text() } else { # 最后一章直接提取标题后所有p标签 paras <- html_nodes(titulo_nodes[i], xpath = "following-sibling::p") %>% html_text() } # 生成当前章节的「标题-段落」对应数据 tibble( titulo = titulo_actual, contenido = paras ) })
代码逻辑说明
- 一次性读取目标页面完整HTML结构,避免重复请求站点
- 通过XPath路径规则,匹配每个标题下属的全部段落,保证段落和所属标题的对应关系准确
- 按章节生成对应数据块后合并为完整数据框,最终输出的
final里每一行对应一段内容,titulo列为该段落所属的章节标题
内容的提问来源于stack exchange,提问作者JMToral
相关产品推荐
相关产品推荐

