python - 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/> 分割的段落文本?
解决方案
尝试这个
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)
推荐阅读
- scala - Scala Spark Convert Dataframe 并从每一行获取所有唯一 ID 及其类型
- javascript - 在 rt.t_start 和 rt.end 相等的情况下看到很长的 BoomerangJS t_done 时间
- python - 所有按钮框和文本都是黑色的
- javascript - 如何在D3中拖放一个圆圈?
- java - 这个java代码如何计算事物的数量?
- python - 如何使用 alpaca_trade_api 获得拆分和股息调整后的价格?
- java - userPreferences 行为怪异,没有保存或检索所有键值,我做错了什么?
- python - 如何使创建帐户的代码免受 SQL 注入的影响?
- typescript - 对象内函数中的泛型
- redmine - 如何在屏幕上轻松查看 redmine 的所有内容,例如项目和票证?