如何从单段HTML中提取键值对(附R语言实现尝试)
从单段落HTML中提取带标记的键值对
场景说明:
需要从HTML文件中提取键值对,但所有信息都集中在单个<p>段落内,仅通过<strong>标记高亮显示键,没有对应每个键值对的独立HTML节点(如div)。目标是将键值对整理为数据框的两列,或两个等长列表,要求key 1对应value 1,key 2对应合并后的value 2a和value 2b,key 3对应value 3,同时处理文件中不一致的换行问题。
以下是将HTML视为原始文本的初步实现方案:
library(tidyverse) library(rvest) html <- minimal_html( "<p> <strong>key 1</strong> value 1 <br></br> <strong>key 2</strong> value 2a <br></br> value 2b <br></br> <strong>key 3</strong> <br></br> value 3 </p>" ) # 以原始文本处理的临时方案 s <- html |> html_elements("p") |> as.character() parse_html <- function(s) { s |> read_html() |> html_text2() } s |> str_replace_all("<strong>(.*)</strong>", "✂️\\1🔧") |> str_split_1("✂️") |> map_chr(parse_html) |> discard(\(x) str_length(x) == 0L) |> str_split("🔧") |> map(str_squish) #> [[1]] #> [1] "key 1" "value 1" #> #> [[2]] #> [1] "key 2" "value 2a value 2b" #> #> [[3]] #> [1] "key 3" "value 3"
Created on 2024-01-18 with reprex v2.1.0
内容的提问来源于stack exchange,提问作者dufei
相关产品推荐
相关产品推荐

