python - 如何使用 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)
解决方案
您可以使用.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']
推荐阅读
- r - 如何引用多个数据框列来计算 R 中的加权平均值的新列
- python - 以父子格式将excel数据导入django数据库
- apache-spark - 为什么这个简单的 Spark 应用程序会创造这么多工作?
- typescript - 通过 ClearScript 将 System.Data.DataTable 暴露到 JS 中后,我如何为 TypeScript 表达它的对象?
- angular - 离子选择/离子标签未正确显示,属性在 Ionic 4 中浮动
- django - 如何在 django 中访问模板内的选定数据?
- flutter - 模仿 iOS 13 全屏对话框
- java - 使用 InputStream 下载大文件
- python-3.x - 如何合并具有相同长度的二维列表
- flutter - 在颤动中溢出 230 像素