【问题标题】:Get text before <br/> python/bs4在 <br/> python/bs4 之前获取文本
【发布时间】:2014-08-24 21:02:39
【问题描述】:

我正在尝试从一个网页中抓取一些数据。标签文本中有换行符和&lt;br/&gt; 标签。我只想获取标签开头的电话号码。你能给我一个建议如何只得到这个数字吗?

这是 HTML 代码:

<td>
    +421 48/471 78 14



    <br />
    <em>(bowling)</em>
</td>

beautifulsoup 有没有办法在标签中获取文本,但只有那个文本,它没有被其他标签包围?第二件事:摆脱文本换行符和 html 换行符?

我用的是 BS4。

输出将是:'+421 48/471 78 14'

你有什么想法吗? 谢谢

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:
    html="""
    <td>
        +421 48/471 78 14
    
    
    
        <br />
        <em>(bowling)</em>
    </td>
    """
    
    
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html)
    
    print soup.find("td").contents[0].strip() 
    +421 48/471 78 14
    
    print soup.find("td").next_element.strip()
    +421 48/471 78 14
    

    soup.find("td").contents[0].strip() 找到我们获取第一个元素的tag 的内容,并使用str.strip() 删除所有\n 换行符。

    来自文档next_element

    字符串或标签的 .next_element 属性指向之后立即解析的内容

    【讨论】:

      【解决方案2】:

      它对你有用吗?

      >>> from bs4 import BeautifulSoup
      >>> str = str.replace("\n", "") # get rid of newlines
      >>> str = "<td>   +421 48/471 78 14    <br /><em>(bowling)</em></td>"
      >>> for item in soup.td.children:
      ...   phone = item # first item is the phone number
      ...   break
      ... 
      >>> phone
      u'   +421 48/471 78 14    '
      >>> phone.strip()
      u'+421 48/471 78 14'
      >>> 
      

      【讨论】:

      • 不,它没有。问题可能是您的字符串中有空格,但我的字符串包含如上面代码中的换行符(在
        标签之前。
      • 然后你可以去掉换行符:str = str.replace("\n", "")
      【解决方案3】:

      另一种方法是使用 decompose() method 删除标签 (从树中删除一个标签,然后完全销毁它及其内容)

      from bs4 import BeautifulSoup
      
      string = '''
      <td>
          +421 48/471 78 14
      
      
      
          <br />
          <em>(bowling)</em>
      </td>
      '''
      
      soup = BeautifulSoup(string, 'html.parser')
      em = soup.select_one('em').decompose()
      
      phone = soup.select_one('td').text.strip()
      print(phone)
      

      输出:

      +421 48/471 78 14
      

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 1970-01-01
        • 2020-01-29
        • 2018-07-21
        相关资源
        最近更新 更多