首页 文章

使用BeautifullSoup修改后保留html文件结构

提问于
浏览
2

我使用python和BeautifullSoup来查找和替换html页面上的一些文本,我的问题是我需要保持文件结构(缩进,空格,换行等)不变并仅更改所需的元素 . 我怎样才能做到这一点? str(soup)soup.prettify() 都在以多种方式改变源文件 .

附:示例代码:

soup = BeautifulSoup(text)
        for element in soup.findAll(text=True):
            if not element.parent.name in ['style', 'script', 'head', 'title','pre']:
                element.replaceWith(process(element))
    result = str(soup)

1 回答

  • 2

    我不容易(或根本没办法) . 来自 BeautifulStoneSoup 的文档:

    __str__(self, encoding='utf-8', prettyPrint=False, indentLevel=0)
        Returns a string or Unicode representation of this tag and
        its contents. To get Unicode, pass None for encoding.
    
        NOTE: since Python's HTML parser consumes whitespace, this
        method is not certain to reproduce the whitespace present in
        the original string.
    

    根据该说明,原始的空白在内部表示中丢失 .

相关问题