BeautifulSoup:如何将内容替换为in span标记

2024-10-16 20:44:59 发布

您现在位置:Python中文网/ 问答频道 /正文

........<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; text-indent:0px;">textHere

<span style=" font-family:'Noto Sans';">ABC</span></p>

<p style=" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; text-indent:0px;"><span style=" font.......

我有一个类似上面的HTML。我需要

  1. 查找“Noto Sans”字体系列中的所有内容(它们总是在span标记内)
  2. 替换它们(A为X,B为Y等)而不改变其余的代码

我试过这个,但没有正常工作。在

^{pr2}$

有什么想法吗?在


Tags: textmarginrightstyletopfamilyleftspan
1条回答
网友
1楼 · 发布于 2024-10-16 20:44:59

您需要找到所有span内有font-family: Noto Sans的标记,然后在找到的每个span元素中用A替换{}:

import re

from bs4 import BeautifulSoup


source_code = """.....<span style=" font-family:'Noto Sans';">ABC</span></p>......"""    
soup = BeautifulSoup(source_code, "lxml")

for elm in soup.find_all('span', style=re.compile(r"font-family:'Noto Sans'")):
    elm.string = elm.text.replace("A", "X")

print(soup.prettify())

印刷品:

^{pr2}$

相关问题 更多 >