我正在使用 Beautiful Soup 来替换文本。
这是我的代码示例:
for x in soup.find('body').find_all(string=True):
fix_str = re.sub(...)
x.replace_with(fix_str)
如何跳过 script和 comment ( <--! --> ) 标签?
我如何确定哪些元素或标签在 x 中? ?
请您参考如下方法:
如果您获取每个文本项的父项,您就可以确定它是否来自 <script> 中。标记或来自 HTML 注释。如果不是,则该文本可用于调用 replace_with()使用你的 re.sub()功能:
from bs4 import BeautifulSoup, Comment
html = """<html>
<head>
<!-- a comment -->
<title>A title</title>
<script>a script</script>
</head>
<body>
Some text 1
<!-- a comment -->
<!-- a comment -->
Some text 2
<!-- a comment -->
<script>a script</script>
Some text 2
</body>
</html>"""
soup = BeautifulSoup(html, "html.parser")
for text in soup.body.find_all(string=True):
if text.parent.name != 'script' and not isinstance(text, Comment):
text.replace_with('new text') # add re.sub() logic here
print soup
为您提供以下新的 HTML:
<html>
<head>
<!-- a comment -->
<title>A title</title>
<script>a script</script>
</head>
<body>new text<!-- a comment -->new text<!-- a comment -->new text<!-- a comment -->new text<script>a script</script>new text</body>
</html>
