我需要在“文本”级别的 HTML 文件中进行一些替换,也就是说,我不能使用 HTML 解析器,因为我没有使用标签。
例如,我需要替换var hls = new Hls(config);与
var config = {
xhrSetup: function(xhr, url){
xhr.withCredentials = true;
}
}
var hls = new Hls(config);
我发现 replace函数,当匹配像 </script>\n</body> 这样的多行字符串时考虑到空格,例如在 </script> 之前添加一些内容
</script>
</body>
</html>
我需要replace('</script>\n </body>', 'alert(1);\n</script>\n</body>') .
由于我将处理不同的文件,有些文件可能使用 2 个字符缩进,其他的使用 4 个字符缩进...我有兴趣删除所有前导空格,以便前面的代码片段变为:
var config = {
xhrSetup: function(xhr, url){
xhr.withCredentials = true;
}
}
var hls = new Hls(config);
或
</script>
</body>
</html>
然后,独立于文件,我可以 replace('</script>\n</body>', 'alert(1);\n</script>\n</body>')
我尝试使用 lstrip()但它似乎没有做任何事情。即:
with open('web.html') as web_page:
web = web_page.read()
print(web.lstrip())
不会删除前导空格。 replace(' ', '')不是一个选项,因为它会破坏代码(例如 varconfig={ )。
TL;DR; 我如何读取 Web 文件并删除 Python 中的所有前导空格?
请您参考如下方法:
您的代码的问题在于您读取 整个 HTML 文件并 lstrip 整个文件,即您只剥离了第一行(可能没有无论如何都有任何缩进)。
相反,您必须单独读取行或在读取后拆分行,然后将 lstrip 应用于每一行。
for line in web_page: # read file one line at a time
print(line.lstrip())
# read file en block, but split lines afterwards
print("\n".join(map(str.lstrip, web.splitlines())))
或者使用正则表达式 ^\s+ 表示“行首的空格”:
import re
print(re.sub(r"^\s+", "", web, flags=re.M))
但除了删除前导空格之外,您还可以使用正则表达式进行实际替换,使用 \s* 表示任意数量的空格,使用 \1重新插入匹配的确切文本,包括原始空格。
print(re.sub(r"(</script>\s*</body>)", r"alert(1);\1", web, flags=re.M))
