【问题标题】:BeautifulSoup: how to replace content with in span tagBeautifulSoup:如何用跨度标签替换内容
【发布时间】:2015-09-14 14:42:54
【问题描述】:
........<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 等...)

我试过的是这个,但不能正常工作。

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

for re in soup.findAll('font', 'face' = "Noto Sans"):
    print (re.replace("A", "X"))

有什么想法吗?

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    您需要找到内部包含font-family: Noto Sans 的所有span 标签,然后在您找到的每个span 元素中将A 替换为X

    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())
    

    打印:

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

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2021-09-17
      • 2014-06-19
      • 1970-01-01
      相关资源
      最近更新 更多