首页 > 解决方案 > 如何在beautifulsoup中找到包含某些粗体文本的标签的索引?

问题描述

在 HTML 中,我想找到包含粗体文本“风险因素”的标签的索引。我的文件格式不同,但它们有一些相似之处。这里有些例子:

<TABLE width="100%" border="0" cellpadding="2" cellspacing="0" style="font-size: 10pt; background: transparent; color: #000000">
<TR valign="top">
    <TD nowrap width="5%"><B>Item&nbsp;1A.</B></TD>
    <TD width="1%">&nbsp;&nbsp;</TD>
    <TD width="94%"><B>Risk Factors</B></TD>
</TR>
</TABLE>

或者

<DIV align="left" style="font-size: 11.5pt;color: #000000; background: #ffffff; margin-top: 12pt; margin-left: 0; margin-right: 0; margin-bottom: 0; ">
<B><FONT color="#002868">Item&nbsp;1A.</FONT> <BR>
 Risk Factors</B>
</DIV>

或者

<DIV align="left" style="font-size: 11pt;color: #000000; background: #ffffff;">
<B><I>Risk Factors</I></B>
</DIV>

请注意,在最后一个示例中,<B> 标记不直接包含文本,而是通过 <I> 标记包含文本。我必须限制为粗体文本,因为其他标签可能包含包含非粗体“风险因素”的不相关文本。

谢谢你。

标签: htmlbeautifulsouphtml-parsing

解决方案


我希望我正确理解了您的问题:您想查找父级<div><table>标签,其中<b>包含字符串“风险因素”的标签:

from bs4 import BeautifulSoup


html_text = '''
<TABLE width="100%" border="0" cellpadding="2" cellspacing="0" style="font-size: 10pt; background: transparent; color: #000000">
<TR valign="top">
    <TD nowrap width="5%"><B>Item&nbsp;1A.</B></TD>
    <TD width="1%">&nbsp;&nbsp;</TD>
    <TD width="94%"><B>Risk Factors</B></TD>
</TR>
</TABLE>


<DIV align="left" style="font-size: 11.5pt;color: #000000; background: #ffffff; margin-top: 12pt; margin-left: 0; margin-right: 0; margin-bottom: 0; ">
<B><FONT color="#002868">Item&nbsp;1A.</FONT> <BR>
 Risk Factors</B>
</DIV>

<DIV align="left" style="font-size: 11pt;color: #000000; background: #ffffff;">
<B><I>Risk Factors</I></B>
</DIV>'''

soup = BeautifulSoup(html_text, 'html.parser')

for tag in soup.find_all(lambda t: t.name == 'b' and 'risk factors' in t.get_text().lower()):
    print(tag.find_previous(['div', 'table']))
    print('-' * 80)

印刷:

<table border="0" cellpadding="2" cellspacing="0" style="font-size: 10pt; background: transparent; color: #000000" width="100%">
<tr valign="top">
<td nowrap="" width="5%"><b>Item 1A.</b></td>
<td width="1%">  </td>
<td width="94%"><b>Risk Factors</b></td>
</tr>
</table>
--------------------------------------------------------------------------------
<div align="left" style="font-size: 11.5pt;color: #000000; background: #ffffff; margin-top: 12pt; margin-left: 0; margin-right: 0; margin-bottom: 0; ">
<b><font color="#002868">Item 1A.</font> <br/>
 Risk Factors</b>
</div>
--------------------------------------------------------------------------------
<div align="left" style="font-size: 11pt;color: #000000; background: #ffffff;">
<b><i>Risk Factors</i></b>
</div>
--------------------------------------------------------------------------------

推荐阅读