customize BeautifulSoup's prettify by tag

前端 未结 2 2167
梦毁少年i
梦毁少年i 2021-02-13 20:43

I was wondering if it would be possible to make it so that prettify did not create new lines on specific tags.

I would like to make it so that span

2条回答
  •  生来不讨喜
    2021-02-13 21:07

    I'm posting a quick hack while I don't find a better solution.

    I'm actually using it on my project to avoid breaking textareas and pre tags. Replace ['span', 'a'] with the tags on which you want to prevent indentation.

    markup = """"""
    
    # Double curly brackets to avoid problems with .format()
    stripped_markup = markup.replace('{','{{').replace('}','}}')
    
    stripped_markup = BeautifulSoup(stripped_markup)
    
    unformatted_tag_list = []
    
    for i, tag in enumerate(stripped_markup.find_all(['span', 'a'])):
        unformatted_tag_list.append(str(tag))
        tag.replace_with('{' + 'unformatted_tag_list[{0}]'.format(i) + '}')
    
    pretty_markup = stripped_markup.prettify().format(unformatted_tag_list=unformatted_tag_list)
    
    print pretty_markup
    

提交回复
热议问题