删除两个其他字符串之间的字符串

Remove string in between two other strings

我有一个字符串,我需要删除两个其他字符串之间的字符串中的字符。

目前我有以下代码,我不太确定为什么它不起作用。

def removeYoutube(itemDescription):
    itemDescription = re.sub('<iframe>.*</iframe>','',desc,flags=re.DOTALL)
    return itemDescription

它不会删除 和 之间的字符串,包括 .

示例输入(字符串):

"<div style="text-align: center;"><iframe allowfullscreen="frameborder=0" height="350" src="https://www.youtube.com/embed/EKaUJExxmEA" width="650"></iframe></div>"

预期输出:<div style="text-align: center;"></div>

正如您从输出中看到的那样,它应该删除所有包含 <iframe></iframe>.

的部分

使用 BeautifulSoup 而不是 regex,因为 regex 是解析 HTML 的糟糕选择。 Here's why.

方法如下:

from bs4 import BeautifulSoup

sample = """
<div style="text-align: center;"><iframe allowfullscreen="frameborder=0" height="350" src="https://www.youtube.com/embed/EKaUJExxmEA" width="650"></iframe></div>
"""

s = BeautifulSoup(sample, "html.parser")

for tag in s.find_all(True):
    if tag.name == "iframe":
        tag.extract()
print(s)

输出:

<div style="text-align: center;"></div>