【问题标题】:How do I remove comments from inside a "script" element but not the rest of the HTML?如何从“脚本”元素中删除注释,而不是 HTML 的其余部分?
【发布时间】:2017-07-11 18:44:24
【问题描述】:

如何只针对脚本元素内部的 cmets,而不是所有“双斜线” cmets,例如,这样:

<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 属性中的链接。

【问题讨论】:

    标签: python html regex python-3.x comments


    【解决方案1】:

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

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

    demo

    【讨论】:

    • 感谢您的回答,我已经对其进行了一些修改以使(?&lt;![ps]\:)\/\/.*\n 现在可以完美运行。再次感谢 +1。
    【解决方案2】:

    试试:

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

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

    【讨论】:

    • 感谢您抽出宝贵时间回答这个问题,但无论哪种方式,它都无法按照我的需要工作,谢谢 +1。
    【解决方案3】:

    隔离你的脚本标签:

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

    【讨论】:

    • 感谢您的帮助,这个答案是有道理的,但不幸的是我没有在这个项目中使用 BeautifulSoup。尽管如此,这是一个很好的答案 +1。
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    相关资源
    最近更新 更多