python如何清除html文件中的内容

python清除html文件中内容的方法:1、使用join方法,代码为【pat = re.compile('>(.*?)<')''.join(pat.findall(test))】;2、使用compile方法。

python如何清除html文件中的内容

本教程操作环境:windows7系统、python3.9版,DELL G3电脑,该方法适用于所有品牌电脑。

python清除html文件中内容的方法:

方法1:

In [97]: str_ = &#39;&#39;
    ...: flag = 1
    ...: for ele in test:
    ...:     if ele == "<":
    ...:         flag = 0
    ...:     elif ele == &#39;>&#39;:
    ...:         flag = 1
    ...:         continue
    ...:     if flag == 1:
    ...:         str_ += ele
    ...:         
In [98]: str_
Out[98]: &#39;just for testjust for testtest&#39;
In [99]: str_ = &#39;&#39;
    ...: flag = 1
    ...: for ele in test:
    ...:     if ele == "<":
    ...:         flag = 0
    ...:     elif ele == &#39;>&#39;:
    ...:         flag = 1
    ...:         ele = &#39; &#39;
    ...:     if flag == 1:
    ...:         str_ += ele
    ...:         
In [100]: str_
Out[100]: &#39; just for test   just for test  test &#39;

方法2:

import re
In [156]: pat = re.compile(&#39;(?<=\>).*?(?=\<)&#39;)
In [157]: pat.findall(test)
Out[157]: [&#39;just for test&#39;, &#39;&#39;, &#39;&#39;, &#39;just for test&#39;, &#39;&#39;, &#39;test&#39;]
In [158]: &#39;&#39;.join(pat.findall(test))
Out[158]: &#39;just for testjust for testtest&#39;

方法3:

pat = re.compile(&#39;>(.*?)<&#39;)
&#39;&#39;.join(pat.findall(test))

方法4:

In [167]: pat = re.compile(&#39;<[^>]+>&#39;, re.S)
In [168]: pat.sub(&#39;&#39;, test)
Out[168]: &#39;just for testjust for testtest&#39;

大量免费学习推荐,敬请访问python教程(视频)

以上就是python如何清除html文件中的内容的详细内容,更多请关注其它相关文章!