当前位置: 代码迷 >> python >> Python-使用正则表达式删除HTML标签
  详细解决方案

Python-使用正则表达式删除HTML标签

热度:47   发布时间:2023-06-13 16:57:09.0

这通常不是一项艰巨的任务,但是今天我似乎无法删除一个简单的javascript标签。

我正在使用的示例(格式化)

<section class="realestate oca"></section>
<script type="text/javascript" data-type="ad">
    window.addEventListener('DOMContentLoaded', function(){
        window.postscribe && postscribe(document.querySelector(".realestate"),
        '<script src="https://ocacache-front.schibsted.tech/public/dist/oca-loader/js/ocaloader.js?type=re&w=100%&h=300"><\/script>');
    });
</script>

我正在使用的示例(原始)

<section class="realestate oca"></section>\n<script type="text/javascript" data-type="ad">\n\twindow.addEventListener(\'DOMContentLoaded\', function(){\n\t\twindow.postscribe && postscribe(document.querySelector(".realestate"),\n\t\t\'<script src="https://ocacache-front.schibsted.tech/public/dist/oca-loader/js/ocaloader.js?type=re&w=100%&h=300"><\\/script>\');\n\t});\n</script>

我想从<script (第二行的开头)到</script> (最后一行)中删除所有内容。 这将仅输出第一行<section..>

这是我的代码行:

re.sub(r'<script[^</script>]+</script>', '', text)
#or
re.sub(r'<script.+?</script>', '', text)

我显然缺少了一些东西,但看不到。
注意:我正在使用的文档主要包含纯文本,因此不需要使用lxml或类似文件进行解析。

您的第一个正则表达式不起作用,因为字符类( [...] )是字符集合 ,而不是字符串。 因此,仅当找到由不包含</sc等的任何字符的字符串分隔的<script</script> ,它才会匹配。

您的第二个regex更好,并且它不起作用的唯一原因是因为默认情况下是. 通配符与换行符不匹配。 要告诉它您想要它,您需要添加标志:

re.sub(r'<script.+?</script>', '', text, flags=re.DOTALL)
  相关解决方案