在某些情况下,Beautiful Soup虽然能够抓取HTML标签,但未能删除所有的Script标签。为了解决这个问题,我们需要使用正则表达式来移除它们。
以下是使用正则表达式在Beautiful Soup中删除Script标签的示例代码:
import re from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
for script in soup(["script"]): # 正则表达式匹配Script标签 match = re.search(r'//|', str(script)) # 删除匹配的Script标签 if match: script.extract()
print(soup.prettify())
在这个示例中,我们首先创建了一个Beautiful Soup对象,并使用正则表达式来删除匹配Script标签的所有内容。我们使用正则表达式模式//|,把包含了'//”和'”子串的Script标签删除。最后,我们打印输出Beautiful Soup对象,以便查看更新后的结果。