使用rvest爬取不同div类内容并整合为带子元素的分组列表
实现思路
你之前的代码存在核心缺陷:分别从整页抓取editor-type和editor节点时,丢失了DOM树中两类节点的邻接从属关系,两个独立向量的顺序没有绑定逻辑,直接拼接必然出现分组错位。
正确的实现逻辑是顺着DOM节点的位置建立归属:每个editor节点归属于它之前最近的那个editor-type节点,直到遇到下一个editor-type节点为止。
方法1:XPath 邻接匹配(代码最简洁)
通过XPath的节点计数逻辑,直接为每个编辑匹配对应的职位类型,不需要写冗余的位置判断:
library(rvest) library(magrittr) webpage <- read_html("https://www.journals.elsevier.com/electoral-studies/editorial-board") # 提取所有职位类型名称,作为列表的顶层元素 type_names <- webpage %>% html_elements(xpath = "//div[@class='editor-type']") %>% html_text2() # 为每个职位类型匹配对应的编辑列表 list_of_editors <- lapply(seq_along(type_names), function(idx) { webpage %>% # 匹配规则:class为editor的节点,前面累计出现的editor-type节点数等于当前索引值 html_elements(xpath = sprintf( "//div[@class='editor'][count(preceding-sibling::div[@class='editor-type']) = %d]", idx )) %>% html_elements(".editor-name h3") %>% html_text2() }) # 为列表元素加上对应的职位类型名称 names(list_of_editors) <- type_names
方法2:顺序遍历分组(逻辑最直观)
如果不想写复杂XPath语法,可以按页面渲染顺序把所有相关节点拉平,逐节点判断归属,对页面结构变动的鲁棒性更强:
# 按页面出现顺序抓取所有editor-type和editor类的节点 all_relevant_nodes <- webpage %>% html_elements(xpath = "//div[@class='editor-type' or @class='editor']") grouped_result <- list() current_type <- NULL for (node in all_relevant_nodes) { node_class <- xml2::xml_attr(node, "class") if (node_class == "editor-type") { # 遇到新的职位类型,初始化新的空分组 current_type <- html_text2(node) grouped_result[[current_type]] <- character(0) } else if (node_class == "editor") { # 遇到编辑节点,把姓名追加到当前分组 editor_name <- node %>% html_elements(".editor-name h3") %>% html_text2() grouped_result[[current_type]] <- c(grouped_result[[current_type]], editor_name) } }
效果验证
两种方法输出的结构和你给出的示例完全一致:
str(list_of_editors) # List of 3 # $ Editors : chr [1:2] "Otto Heath" "Kathrin Smets" # $ Associate Editor : chr [1:2] "Rosa Dassonville" "Matthias Wagner" # $ Editorial Assistant: chr [1] "Markus Polacko"
避坑提醒
不要直接把单独抓取的editor_names向量按固定计数拆分组——每个职位类型对应的编辑数量不是固定值,没有明确的归属匹配逻辑的话,只要页面结构有微调(比如多了一个编辑、两个type之间夹了非核心内容节点)就会出现全链路错位。
内容的提问来源于stack exchange,提问作者anpami
相关产品推荐
相关产品推荐

