可以通过使用CSS选择器来获取表格中每个单元格的文本内容并手动处理换行符。例如:
from bs4 import BeautifulSoup
html = """
Cell 1
Cell 2
Cell 3
Cell 4
with a linebreak
"""
soup = BeautifulSoup(html, 'html.parser')
for row in soup.select('tr'):
cells = row.select('td')
for cell in cells:
text = ''
for content in cell.contents:
if str(content) != '
':
text += str(content).strip()
else:
text += '\n'
print(text)
在上面的示例中,我们使用CSS选择器获取表格中每个行的单元格,并手动处理了单元格中的换行符。输出结果为:
Cell 1
Cell 2
Cell 3
Cell 4
with a linebreak