【问题标题】:Smart prettify html with BeautifulSoup使用 BeautifulSoup 智能美化 html
【发布时间】:2021-12-03 18:32:59
【问题描述】:

有什么方法可以控制展开的深度吗?我的 HTML 有时包含 css。并且美化为每个标签添加换行符...

<html><body><h1>hello world</h1></body></html>

到:

<html>
 <body><h1>hello world</h1></body>
</html>
from bs4 import BeautifulSoup

INPUT_FILE = "html_unformatted.txt"
OUTPUT_FILE = "index.html"

unicode_data = open(INPUT_FILE, "r", encoding='unicode_escape').read()
data = unicode_data.encode('iso-8859-1').decode('utf-8')
soup = BeautifulSoup(data, features="html.parser")
pretty_html = soup.prettify()

with open(OUTPUT_FILE, "w") as f:
    f.write(pretty_html)
    print(f"Wrote to {OUTPUT_FILE}")

我有:


<html>
 <body>
  <h1>
   hello world
  </h1>
 </body>
</html>

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    不幸的是,根据beautifulsoup docs 的说法,自定义prettify 函数不是一种选择。但是,可以将soup.prettify 包装到另一个函数中,并将“漂亮”的文本替换为单行文本。

    这就是下面的prettify_except 所做的,即美化除tag_name 中包含的文本之外的任何内容:

    from bs4 import BeautifulSoup
    import re
    
    html = "<html><body><h1>hello world</h1></body></html>"
    soup = BeautifulSoup(html, features="html.parser")
    
    print(soup.prettify())
    
    def prettify_except(soup_obj: BeautifulSoup, tag_name: str) -> str:
        regex_string = "<{0}>.*<\/{0}>".format(tag_name)
        regex = re.compile(regex_string, re.DOTALL)
        replacing_txt = str(getattr(soup_obj, tag_name))
        return re.sub(regex, replacing_txt, soup_obj.prettify())
    
    print(prettify_except(soup, 'body'))
    
    # original prettified
    
    # <html>
    #  <body>
    #   <h1>
    #    hello world
    #   </h1>
    #  </body>
    # </html>
    
    
    # prettified, except body
    
    # <html>
    #  <body><h1>hello world</h1></body>
    # </html>
    

    【讨论】:

      猜你喜欢
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      • 2021-04-20
      相关资源
      最近更新 更多