【问题标题】:Beautiful Soup skip comment and script tagsBeautiful Soup 跳过评论和脚本标签
【发布时间】:2018-04-26 22:42:19
【问题描述】:

我正在使用 Beautiful Soup 替换文本。

这是我的代码示例:

for x in soup.find('body').find_all(string=True):
   fix_str = re.sub(...)
   x.replace_with(fix_str)

如何跳过scriptcomment (<--! -->) 标签?

如何确定x 中有哪些元素或标签?

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

如果您获取每个文本项的父项,则可以确定它是来自<script> 标记内还是来自 HTML 注释。如果没有,则可以使用您的re.sub() 函数使用该文本调用replace_with()

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>

【讨论】:

  • thx,但是我不能使用方法 replace_with 替换文本。我需要在除注释和脚本之外的所有地方替换文本,并返回包含此标签的完整 html
  • 啊,我明白了。我已经更新了脚本以允许它修改文本。
猜你喜欢
  • 2014-06-11
  • 2011-07-11
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
相关资源
最近更新 更多