我使用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 回答
我不容易(或根本没办法) . 来自
BeautifulStoneSoup
的文档:根据该说明,原始的空白在内部表示中丢失 .