You need to enable JavaScript to run this app. Python中如何拆分包含连续SVG标签的长HTML字符串
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何拆分包含连续SVG标签的长HTML字符串

HTML长字符串拆分方案

你提供的字符串中每个待拆分的独立块有明确的结构特征:每个有效单元以带有data-type="coordinates"属性的svg标签开头,内部嵌套三层svg节点后以连续三个</svg>闭合,以下是两种可行的Python实现:

方案一:使用HTML解析库实现(推荐)

稳定性更高,不会因为标签格式的微小变化(比如空格、换行)匹配失败,需要先安装依赖:
pip install beautifulsoup4

实现代码:

import html
from bs4 import BeautifulSoup

# 替换为你的原始长HTML字符串
raw_html_str = """你的长HTML内容"""
# 转义HTML实体(把&quot;这类编码转回正常字符)
decoded_content = html.unescape(raw_html_str)

# 解析HTML
soup = BeautifulSoup(decoded_content, 'html.parser')
# 查找所有坐标类型的svg节点
coordinate_svg_nodes = soup.find_all('svg', attrs={'data-type': 'coordinates'})
# 转换为字符串列表
split_result = [str(node) for node in coordinate_svg_nodes]

# 若需要保留第一个坐标svg之前的截断内容,添加以下代码
first_svg_index = decoded_content.find('<svg ')
if first_svg_index > 0:
    prefix_content = decoded_content[:first_svg_index].strip()
    if prefix_content:
        split_result.insert(0, prefix_content)

print(split_result)

方案二:正则匹配实现(无需额外依赖)

适合轻量场景,代码更简洁:

import re
import html

# 替换为你的原始长HTML字符串
raw_html_str = """你的长HTML内容"""
decoded_content = html.unescape(raw_html_str)

# 正则匹配每个坐标svg块,re.DOTALL让.可以匹配换行符
pattern = re.compile(
    r'<svg[^>]*data-type="coordinates"[^>]*>.*?</svg>\s*</svg>\s*</svg>',
    re.DOTALL
)
split_result = pattern.findall(decoded_content)

# 若需要保留第一个坐标svg之前的截断内容,添加以下代码
if split_result:
    first_match_index = decoded_content.find(split_result[0])
    if first_match_index > 0:
        prefix_content = decoded_content[:first_match_index].strip()
        if prefix_content:
            split_result.insert(0, prefix_content)

print(split_result)

两种方案输出的列表结构与你提供的拆分示例完全一致,如果后续svg嵌套层数有调整,只需要对应修改正则中匹配的</svg>数量,或者BeautifulSoup的节点查找规则即可。

内容的提问来源于stack exchange,提问作者Kate shim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 16:15:04