python - 用 python 函数包装 html

标签 python html parsing

我希望能够根据 div 的 id 对其进行包装。例如,给出以下 HTML:

<body>
    <div id="info">
        <div id="a1">
        </div>
        <div id="a2">
            <div id="description">
            </div>
            <div id="links">
                <a href="http://example.com">link</a>
            </div>
        </div>
    </div>
</body>

我想编写一个带有文档、id 和选择器的 Python 函数。并将给定 document 中的给定 id 包装在带有类或 id selectordiv 中。例如,假设上面的 HTML 位于变量 doc

wrap(doc,'#a2','#wrapped')

将返回以下 HTML:

<body>
    <div id="info">
        <div id="a1">
        </div>
        <div id="wrapped">
            <div id="a2">
                <div id="description">
                </div>
                <div id="links">
                    <a href="http://example.com">link</a>
                </div>
            </div>
        </div>
    </div>
</body>

我查看了一些 XML 解析器和 Python HTMLParser,但我没有找到任何东西可以让我不仅能够获取特定标签内的所有内容,而且还能够附加字符串并轻松编辑文档。如果不存在,什么是一个好的方法?

最佳答案

from BeautifulSoup import BeautifulSoup

#div1 is to be wrapped with div2
def wrap(doc,div1_id,div2_id)
    pool = BeautifulSoup(doc)
    for div in pool.findAll('div', attrs={'id':div1_id}):
        div.replaceWith('<div id='+div2_id+'>' + div.prettify() + '</div>' )
    return pool.prettify()

wrap(doc,'a2','wrapped')

关于python - 用 python 函数包装 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17564459/

相关文章:

javascript - 单击 Canvas 元素内部选择文本

parsing - MIDI 解析 - 如何知道 0xFF 字节代表什么?

python - 使用 Python 在 Yandex 图像中反向搜索图像

python - 有没有办法在ipython中使用 "less"查看python输出

python - 如何使用 `` xlrd.xldate_as_tuple( )``

Python HTTP 简单服务器持久连接

html - CSS Align Text with Select 在同一行

Python:将 HTML 转换为 AsciiDoc

python - 如何在 Python 中融化或取消堆叠数据帧?

c - gengetopt : Multiple arguments split with space, 不是逗号