使用R将HTML中a标签的TAGS属性从空格分隔改为逗号分隔并写回文件
用R语言转换HTML书签标签格式并保存文件
问题
需要处理Diigo导出的HTML书签文件,将其中<a>标签的TAGS属性值从空格分隔格式改为逗号分隔格式,修改后重新写入文件。Firefox导入空格分隔的标签时会将其识别为单个长标签,无法正确解析为多个独立标签,因此需要做格式转换。
示例HTML数据
<!DOCTYPE NETSCAPE-Bookmark-file-1> <!-- This is an automatically generated file. It will be read and overwritten. DO NOT EDIT! --> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> <TITLE>Bookmarks</TITLE> <H1 LAST_MODIFIED="">Bookmarks</H1> <DL><p> <DT><H3 ID="">Diigo - Nathan Craig's Bookmarks</H3> <DL><p> <DT><A HREF="https://github.com/ahb108/rcarbon/" LAST_MODIFIED="" TAGS="R-Language R-Library radiocarbon" ID="">ahb108/rcarbon: Methods for calibrating and analysing radiocarbon dates</A> <DD> <DT><A HREF="https://docs.ropensci.org/c14bazAAR/index.html" LAST_MODIFIED="" TAGS="R-Language R-Library radiocarbon" ID="">Download and Prepare C14 Dates from Different Source Databases • c14bazAAR</A> <DD> </DL><p> </DL><p>
已完成的步骤
已经成功提取并转换了标签格式,但不知道如何将修改后的标签写回原HTML文件:
library(rvest) library(stringr) library(htmltools) # 读取文件 document <- read_html(here::here("data/links.htm")) # 提取TAGS属性 tags <- document |> html_elements("a") |> html_attr("tags") # 输出: [1] "R-Language R-Library radiocarbon" "R-Language R-Library radiocarbon" # 转换为逗号分隔 str_replace_all(tags, " ", ",") # 输出: [1] "R-Language,R-Library,radiocarbon" "R-Language,R-Library,radiocarbon"
解决方法
通过rvest的html_attr<-赋值操作,直接将转换后的标签值批量设置回<a>标签的TAGS属性,再保存整个文档即可:
library(rvest) library(stringr) library(here) # 1. 读取HTML文件 document <- read_html(here("data/links.htm")) # 2. 选中所有<a>标签 a_elements <- html_elements(document, "a") # 3. 提取并转换标签格式 updated_tags <- str_replace_all(html_attr(a_elements, "tags"), " ", ",") # 4. 将转换后的标签写回<a>标签的TAGS属性 html_attr(a_elements, "tags") <- updated_tags # 5. 保存修改后的HTML文件(建议先存为新文件验证,确认无误后可覆盖原文件) write_html(document, here("data/modified_bookmarks.htm"))
说明
html_attr(a_elements, "tags") <- updated_tags:这一步是核心,直接对选中的所有<a>标签批量更新TAGS属性值。write_html():将修改后的完整HTML文档写入指定路径,注意如果直接覆盖原文件,建议先备份原数据。
内容的提问来源于stack exchange,提问作者ncraig
相关产品推荐
相关产品推荐

