Не может prettify HTML-код с возвышенным текстом, ни красивый суп - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь закопать какой-нибудь сайт для информации.я сохранил страницу, которую я хочу записать как файл .html, и открыл ее с sublime text, но есть некоторые части, которые не могут быть отображены предварительно проверенным способом;У меня такая же проблема при попытке использовать beautifulsoup;см. рисунок ниже (я не могу поделиться полным кодом, поскольку он раскрывает личную информацию).

enter image description here

1 Ответ

0 голосов
/ 07 мая 2019

Просто передайте HTML как многострочную строку объекту BeautifulSoup и используйте soup.prettify(). Это должно работать. Однако Beautifulsoup имеет отступ по умолчанию на 2 пробела. Поэтому, если вы хотите сделать собственный отступ, вы можете написать небольшую обертку, например:

def indentPrettify(soup, indent=4):
    # where desired_indent is number of spaces as an int()
    pretty_soup = str()
    previous_indent = 0
    # iterate over each line of a prettified soup
    for line in soup.prettify().split("\n"):
        # returns the index for the opening html tag '<'
        current_indent = str(line).find("<")
        # which is also represents the number of spaces in the lines indentation
        if current_indent == -1 or current_indent > previous_indent + 2:
            current_indent = previous_indent + 1
            # str.find() will equal -1 when no '<' is found. This means the line is some kind
            # of text or script instead of an HTML element and should be treated as a child
            # of the previous line. also, current_indent should never be more than previous + 1.
        previous_indent = current_indent
        pretty_soup += writeOut(line, current_indent, indent)
    return pretty_soup

def writeOut(line, current_indent, desired_indent):
    new_line = ""
    spaces_to_add = (current_indent * desired_indent) - current_indent
    if spaces_to_add > 0:
        for i in range(spaces_to_add):
            new_line += " "
    new_line += str(line) + "\n"
    return new_line
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...