如何从 "script" 元素中删除评论而不是 HTML 的其余部分?

How do I remove comments from inside a "script" element but not the rest of the HTML?

如何只针对脚本元素内的评论,而不是所有 "double slash" 评论,例如,this:

<a href="https://www.example.com">Link to example.com</a>
<script type="text/javascript">
  // I am a comment, I describe this script
  console.log("Hello World!");
</script>

变成这样:

<a href="https://www.example.com">Link to example.com</a>
<script type="text/javascript">
  console.log("Hello World!");
</script>

到目前为止我有这个:

html = re.sub(re.compile(r"\/\/.*?\n"), "\n", html)

它有效,但它也删除了我在 hrefsrc 属性中的链接。

隔离你的脚本标签:

scripts = bs4_obj.find_all('script')
for script in script:
    # Your regex

尝试:

comments_match = r"[^:]\/\/.+\r?\n" 
print( re.sub(comments_match, "\n", your_html_string) )

查看否定字符的信息 类 - http://www.regular-expressions.info/charclass.html

您可以使用 regexNegative Lookbehind 来完成此操作。所以,下面的代码应该可以做到:

html = re.sub(re.compile(r"(?<!:)\/\/.*\n"), "\n", html)

demo