Как убрать пустое пространство или выровнять влево строку, очищенную через BeautifulSoup?str.strip () или str.ljust () не работает - PullRequest
1 голос
/ 09 апреля 2019

Как убрать или выровнять по левому краю пустое пространство от данных, очищенных с помощью BeautifulSoup? Данные преобразуются в str из Unicode.

пробовал str.strip () и str.ljust (), str.replace ("\ n", ""). Проверка каждого символа на None и отображение, если нет None, также не работает

  from bs4 import BeautifulSoup
  import requests    
  with open('f.html') as f:
    soup=BeautifulSoup(f,'lxml')
    article = soup.findAll('div',class_='modal-content')
    for i in article:
        print (str(i.text).strip())

Получено:

reset to default listTour

                            Start here for a quick overview of the site





                    Help Center

                        Detailed answers to any questions you might have

ожидаемый результат:

 reset to default listTour
 Start here for a quick overview of the site
 Help Center
 Detailed answers to any questions you might have

1 Ответ

1 голос
/ 09 апреля 2019

Это не красиво, но я думаю, что это сработает.

  from bs4 import BeautifulSoup
  import requests    
  with open('f.html') as f:
    soup=BeautifulSoup(f,'lxml')
    article = soup.findAll('div',class_='modal-content')
    for i in article:
        text=str(i.text)
        text=text.split('\n')
        text=[x.strip() for x in text if x.strip()!='']
        output=''
        for t in text:
            output+=t+'\n'
        print(output)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...