Wenn Sie das übergeordnete Element für jedes Textelement nehmen Sie erhalten, können Sie dann bestimmen, ob sie innerhalb eines <script>
Tag oder von einem HTML-Kommentar kommt. Wenn nicht, kann der Text dann verwendet werden, replace_with()
rufen Sie Ihre re.sub()
Funktion:
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
Geben Sie folgende neue 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>
Verwenden Sie BeautifulSoup 4? Siehe https://stackoverflow.com/questions/33138937/how-to-find-all-comments-with-beautiful-soup – Surender
ja ich benutze bs4, thx – User34