2016-11-16 449 views
0

我在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 

回答

0

文本沒有標籤是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>標籤後跟一個字符串),然後根據需要提取信息。

0
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將正常工作