首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用BeautifulSoup删除HTML中多余的类名

使用BeautifulSoup删除HTML中多余的类名
EN

Stack Overflow用户
提问于 2020-03-12 15:28:39
回答 1查看 41关注 0票数 0

我想转换成:

代码语言:javascript
运行
复制
<span class = "foo">data-1</span>
<span class = "foo">data-2</span>
<span class = "foo">data-3</span>

代码语言:javascript
运行
复制
<span class = "foo"> data-1 data-2 data-3 </span>

在Python中使用BeautifulSoup。此HTML部分存在于页面主体的多个区域中,因此我想最小化此部分并将其删除。实际上,mid类是和em类在一起的,所以最初是分开的。

EN

回答 1

Stack Overflow用户

发布于 2020-03-12 16:47:10

改编自this answer,展示了如何将其用于span标记:

代码语言:javascript
运行
复制
span_tags = container.find_all('span')

# combine all the text from b tags
text = ''.join(span.get_text(strip=True) for span in span_tags)

# here you choose a tag you want to preserve and update its text
span_main = span_tags[0]  # you can target it however you want, I just take the first one from the list
span_main.span.string = text  # replace the text

for tag in span_tags:
    if tag is not span_main:
        tag.decompose()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60649387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档