【问题标题】:BeautifulSoup.get_text() ignoring line breaks <br>BeautifulSoup.get_text() 忽略换行符 <br>
【发布时间】:2020-08-08 18:38:31
【问题描述】:

我安装了 beautifulsoup4 (4.9.0) 并尝试解析一些 html。 Python 3.7 版

我正在从一些表格中收集数据,这些表格在单元格中由换行符 &lt;br&gt; 分割,例如:

<td>some text<br>some more text</td>

但是.get_text() 似乎忽略了换行符并将其全部打印到一行:

html = '<td>some text<br>some more text</td>'
soup = BeautifulSoup(html, features='html.parser')

print(soup)
 >> <td>some text<br/>some more text</td>

print(soup.get_text())
 >> some textsome more text

&lt;br&gt; 已转换为 &lt;br/&gt;,但我不太了解 HTML,因此不确定这是否重要。

期望的结果

每个换行符之间的字符串列表。我正在考虑使用.get_text() 方法,然后.split() 通过换行符生成结果字符串,例如:

html = '<td>some text<br>some more text</td>'
soup = BeautifulSoup(html, features='html.parser')
strings = soup.get_text().split('?')
  >> ['some text', 'some more text']

任何人都知道如何让get_text() 识别换行符,以及? 需要是什么?我在想也许可以用一个不会被忽略的明确字符/字符串替换换行符,然后用它拆分。更优雅的解决方案将不胜感激!

谢谢

【问题讨论】:

    标签: python html python-3.x beautifulsoup


    【解决方案1】:

    我的解决方案,如问题中所述。用明确的字符串替换 &lt;br&gt; 标记,然后使用它拆分字符串:

    from bs4 import BeautifulSoup
    
    html = '<td>some text<br>some more text</td>'
    soup = BeautifulSoup(html, features='html.parser')
    delimiter = '###'                           # unambiguous string
    for line_break in soup.findAll('br'):       # loop through line break tags
        line_break.replaceWith(delimiter)       # replace br tags with delimiter
    strings = soup.get_text().split(delimiter)  # get list of strings
      >> ['some text', 'some more text']        # output
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      相关资源
      最近更新 更多