BeautifulSoup для вывода извлеченного текста построчно - PullRequest
2 голосов
/ 24 февраля 2020

html пример ниже, и я использую BeautifulSoup для извлечения текстов.

txt = """[<dd class="qs" id="qsff"><br/>Pretty women wonder where my secret lies. <br/>I'm not cute or built to suit a fashion model's size<br/>But when I start to tell them,<br/>They think I'm telling lies.<br/><br/>I say,<br/>It's in the reach of my arms<br/>The span of my hips,<br/>The stride of my step,<br/>The curl of my lips.<br/><br/></dd>]"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(txt, "lxml")

for node in soup:
    print (node.text)

# [Pretty women wonder where my secret lies. I'm not cute or built to suit a fashion model's sizeBut when I start to tell them,They think I'm telling lies.I say,It's in the reach of my armsThe span of my hips,The stride of my step,The curl of my lips.]

Он показывает мне целый кусок строки, как указано выше, но я хочу, чтобы они были построчно, например:

Pretty women wonder where my secret lies.
I'm not cute or built to suit a fashion model's size
But when I start to tell them,
....

Я пробовал ниже, но это не работает.

for node in soup.find_all('br'):
    print (node.text)

Как правильно выводить их построчно? Спасибо.

1 Ответ

1 голос
/ 24 февраля 2020

Перебирайте строки, а не узлы:

for node in soup.dd.strings:
    print(node)
#Pretty women wonder where my secret lies. 
#I'm not cute or built to suit a fashion model's size
#But when I start to tell them,
#....

А почему вы заключаете текст в квадратные скобки?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...