【问题标题】:Display all b tags inside p tag with BeautifulSoup使用 BeautifulSoup 显示 p 标签内的所有 b 标签
【发布时间】:2016-11-16 16:36:27
【问题描述】:

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

这是我的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里面的所有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

【问题讨论】:

    标签: python regex django beautifulsoup


    【解决方案1】:
    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 tagp tag就可以了

    【讨论】:

      【解决方案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 的孩子并确保它们具有正确的结构(&lt;b&gt; 标记后跟一个字符串),然后根据需要提取信息。

      【讨论】:

        猜你喜欢
        • 2014-10-02
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多