用BeautifulSoup显示p标签内的所有b标签

2024-04-16 14:59:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有django的应用程序,我必须以特定的方式显示文本。在

这是我的html代码:

<p class="name">
<b>Name of person</b> City, Country</p>
<p class="name">
<b>Name of person</b></p>

我想在普通文本中输入粗体的人名和城市和国家,例如:

^{pr2}$

但我只能得到b,怎么能得到p里面的所有p和b呢?在

我在BeautifulSoap中的代码:

people = self.concattexts.filter(code='Active')
for p in people:
    soup = BeautifulSoup(p.text_html, 'html.parser')
    all_people = [b.get_text(separator=' - ', strip=True) for b in soup.find_all('b')]
    return all_people

Tags: ofdjango代码textnamein文本for
2条回答

没有标记的文本是NavigableString

>>> soup = BeautifulSoup('<p class="name"><b>Name of person</b> City, Country</p>',
...                      'html.parser')
>>> children = list(soup.p.children)
>>> children
[<b>Name of person</b>, u' City, Country']
>>> type(children[-1])
<class 'bs4.element.NavigableString'>
>>> isinstance(children[-1], basestring)
True

我建议获取p的子元素,并确保它们具有正确的结构(后跟一个字符串的<b>标记),然后根据需要提取信息。在

from bs4 import BeautifulSoup
doc = '''
<p class="name">
<b>Name of person</b> City, Country</p>
<p class="name">
<b>Name of person</b></p>
'''
soup = BeautifulSoup(doc,'lxml')

for i in soup.find_all('p', class_='name'):
    print(i.get_text(separator=' - ', strip=True))

输出:

^{pr2}$

get_text()可以得到标签下的所有文本,不需要使用b tag,只要{}就可以了

相关问题 更多 >