Skip to main content
 首页 » 编程设计

python之BeautifulSoup 和表格行内的换行符

2025年05月04日18emanlee

示例代码:

from BeautifulSoup import BeautifulSoup, SoupStrainer 
 
html='''<tr> 
<td align="left">Foo<br /> 
Bar<br /></td> 
</tr>''' 
 
soup=BeautifulSoup(html) 
rows=soup.findAll('tr') 
print rows 
print rows[0].text.encode("utf8") 

我希望输出类似于“Foo Bar”,或者即使两行之间有一个实际的换行符也可以,但我得到的输出只有“FooBar”,请注意没有空格两条线之间。

对 python 和 beautifulsoup 非常陌生,有人可以帮忙吗?

请您参考如下方法:

您可以使用 cell = rows[0].find('td') 更进一步, 然后使用 cell.contents 查看其内容,然后过滤你需要的元素,然后join他们用空格。

另一种选择:您可以使用正则表达式来替换 <br />通过一个空间。为此你可以写:

import re 
s = re.sub('<br\s*?>', ' ', rows[0].text) 

然后你可以将多个连续的空格替换为

s = re.sub('\s+', ' ', s) 

那么字符串应该是这样的:

>>> print s 
<tr> <td align="left">Foo Bar </td> </tr> 

然后你就可以轻松的提取你需要的部分了。