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

问题描述:

我在django中有应用程序,我必须以特定方式显示文本。使用BeautifulSoup显示p标签内的所有b标签

这是我的html代码:

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

我想要得到的人,城市和乡村加粗名称在普通的文本,例如:

**Name of person** City, Country 
**Name of person** 

但我只能得到B,我怎么能得到所有p和b在p?

我的代码在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 

文本没有标签是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)) 

出来:

Name of person - City, Country 
Name of person 

get_text()可以得到下面的标签所有文字,就没有必要使用b tag,只是p tag将正常工作