首页 > 解决方案 > 如何使用 beautifulsoup 从 html 中过滤掉我想要的所有“彩色”单词

问题描述

我有如下所示的 html 代码:

<TR>
<TD><P>1-A3</P></TD>
<TD><P>9007320896</P></TD>
<TD><P>140739389</P></TD>
<TD><P>9003911104</P></TD>
<TD><P>140686111</P></TD>
<TD><P>140686111(1-A4)</P></TD>
<TD><P>0</P></TD>
<TD><P>0</P></TD>
</TR>
<TR>
<TD><P><B><FONT COLOR="#FF0000">1-B1</FONT></B></P></TD>
<TD><P><B><FONT COLOR="#FF0000">8799053184</FONT></B></P></TD>
<TD><P><B><FONT COLOR="#FF0000">137485206</FONT></B></P></TD>
</TR>

我想用python提取出所有红色粗体的文本

答:[1-B1,8799053184,137485206]

这是我的代码,我不知道为什么它不起作用

from bs4 import BeautifulSoup
html_doc = """
file_example = open (html_doc)
soup = BeautifulSoup(file_example, 'html.parser')
result2 = soup.findAll('b')
result2 = soup.findAll('font')
bold = soup.select('p', 'b', {'color':'#FF0000'})
haha = list(map(lambda tag: tag.text, bold))
print(haha)

标签: pythonhtmlparsingtextbeautifulsoup

解决方案


您可以使用.select()带有颜色属性#FF0000 的子字体标签来获取粗体标签。

html = '''<TR>
<TD><P>1-A3</P></TD>
<TD><P>9007320896</P></TD>
<TD><P>140739389</P></TD>
<TD><P>9003911104</P></TD>
<TD><P>140686111</P></TD>
<TD><P>140686111(1-A4)</P></TD>
<TD><P>0</P></TD>
<TD><P>0</P></TD>
</TR>
<TR>
<TD><P><B><FONT COLOR="#FF0000">1-B1</FONT></B></P></TD>
<TD><P><B><FONT COLOR="#FF0000">8799053184</FONT></B></P></TD>
<TD><P><B><FONT COLOR="black">this is black</FONT></B></P></TD>
<TD><P><B><FONT COLOR="#FF0000">137485206</FONT></B></P></TD>
<TD><P><B><FONT COLOR="BLUE">Also Not Red</FONT></B></P></TD>
</TR>'''

from bs4 import BeautifulSoup
html_doc = html

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

bold_red = soup.select('b > font[color="#FF0000"]')

haha = [ each.text for each in bold_red ]
print (haha)

输出:

['1-B1', '8799053184', '137485206']

推荐阅读