解析多个.html文件并删除部分html代码的方法

Posted

技术标签:

【中文标题】解析多个.html文件并删除部分html代码的方法【英文标题】:Method to parse multiple .html files and remove part of html code 【发布时间】:2021-10-07 22:40:46 【问题描述】:

解析目录中的多个 .html 文件、搜索和删除这些文件中的部分 html 代码的正确方法是什么? 例如,我需要从所有文件中删除一个 html 代码:

    <div class="box">
        <h2>Book Search</h2>
        <div id="search">
            <form action="http://www.biology35.com/search.php" method="post">
                <input type="text" name="searchfor" class="txtField" />
                <input type="image" src="new/images/btn-go.png" name="Submit" value="Submit" class="button" />
                <div class="clear"><!-- --></div>
            </form>
        </div>
    </div>

我在 Debian 上使用 Geany 1.29 文件编辑器。正则表达式可能不适合这个。一些shell脚本或python?

【问题讨论】:

只复制 HTML 并转义任何在正则表达式中具有特殊含义的字符。这是一个开始:&lt;div class=\"box\"&gt;\s*&lt;h2&gt;Book Search&lt;\/h2&gt;\s*&lt;div id=\"search\"&gt;\s*regex101.com/r/BuPSZr/1 你看过BeautifulSoup吗? @sophros 我已经为 Python 2.x 安装了这个库 BeautifulSoup 4。查看了文档中的一些示例,但由于我以前从未使用过它,因此对于初次使用的用户来说需要大量学习,仍然无法弄清楚如何将其应用到我的任务中。 @MonkeyZeus:作为正则表达式示例,它可以工作并且对我很有帮助,但是我需要编辑的多个 html 文档中的每个文档都有 8 个代码段。不确定如何同时为多个文档完成此操作。 【参考方案1】:

可以使用htql,例如:

html = """
something before
    <div class="box">
        <h2>Book Search</h2>
        <div id="search">
            <form action="http://www.biology35.com/search.php" method="post">
                <input type="text" name="searchfor" class="txtField" />
                <input type="image" src="new/images/btn-go.png" name="Submit" value="Submit" class="button" />
                <div class="clear"><!-- --></div>
            </form>
        </div>
    </div>

html after
"""

import htql
x=htql.query(html, "<div norecur (class='box') > &delete ")[0][0]

你得到:

>>> x
'\nsomething before\n    \n\nhtml after\n'

【讨论】:

以上是关于解析多个.html文件并删除部分html代码的方法的主要内容,如果未能解决你的问题,请参考以下文章

Python解析Wav文件并绘制波形的方法

使用 XSLT 2.0/3.0 使用多个步骤将 CDATA 中的纯文本解析为 html。那里的一部分

深入学习python解析并读取PDF文件内容的方法

HTML里的哪一部分Javascript 会在页面加载的时候被执行?

解析多个HTML标签Bash [重复]

如何解析包含多个标签的html节点?