html - 如何在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 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>
请注意,在最后一个示例中,<B> 标记不直接包含文本,而是通过 <I> 标记包含文本。我必须限制为粗体文本,因为其他标签可能包含包含非粗体“风险因素”的不相关文本。
谢谢你。
解决方案
我希望我正确理解了您的问题:您想查找父级<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 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>'''
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>
--------------------------------------------------------------------------------
推荐阅读
- android - 如何在 Android Studio 中使用 Active Directory 或 LDAP 验证用户名和密码
- python - Python:从对象列表中操作参数。
- excel - VBA 目录在名为“..”或 Documents.xlsx 的目录中提取 Ghost 文件
- neural-network - 在 keras 中实现多元回归器神经网络时出错
- android - 安卓加密。怎么做?
- notepad++ - 如何使用 notepad++ 正则表达式更改 asciidoc 代码块样式?
- javascript - 如何分别从数组 [0] 位置访问对象?
- php - 如何在访问laravel中的任何路由列表之前执行中间件
- gradle - gradle 是否支持“提升”错误?
- ntp - 同步两台机器的最佳服务器