首页 > 解决方案 > BeautifulSoup 从段落中提取文本并拆分文本

问题描述

我对 BeauitfulSoup 很陌生。

我如何能够从 html 源代码中提取段落中的文本,只要有 <br/> 就拆分文本,并将其存储到数组中,这样数组中的每个元素都是段落文本中的一个块(被<br/>分割)?

例如,对于以下段落:

<p>
    <strong>Pancakes</strong>
    <br/> 
    A <strong>delicious</strong> type of food
    <br/>
</p>

我希望将其存储到以下数组中:

['Pancakes', 'A delicious type of food']


我尝试过的是:

import bs4 as bs

soup = bs.BeautifulSoup("<p>Pancakes<br/> A delicious type of food<br/></p>")
p = soup.findAll('p')
p[0] = p[0].getText()
print(p)

但这会输出一个只有一个元素的数组:

['Pancakes A delicious type of food']

有什么方法可以对其进行编码,以便我可以获得一个数组,其中包含由段落中的任何 <br/> 分割的段落文本?

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


尝试这个

from bs4 import BeautifulSoup, NavigableString

html = '<p>Pancakes<br/> A delicious type of food<br/></p>'

soup = BeautifulSoup(html, 'html.parser')
p = soup.findAll('p')
result = [str(child).strip() for child in p[0].children
            if isinstance(child, NavigableString)]

深度递归更新

from bs4 import BeautifulSoup, NavigableString, Tag

html = "<p><strong>Pancakes</strong><br/> A <strong>delicious</strong> type of food<br/></p>"

soup = BeautifulSoup(html, 'html.parser')
p = soup.find('p').find_all(text=True, recursive=True)

再次更新仅由 <br> 分割的文本

from bs4 import BeautifulSoup, NavigableString, Tag

html = "<p><strong>Pancakes</strong><br/> A <strong>delicious</strong> type of food<br/></p>"

soup = BeautifulSoup(html, 'html.parser')
text = ''
for child in soup.find_all('p')[0]:
    if isinstance(child, NavigableString):
        text += str(child).strip()
    elif isinstance(child, Tag):
        if child.name != 'br':
            text += child.text.strip()
        else:
            text += '\n'

result = text.strip().split('\n')
print(result)

推荐阅读