繁体   English   中英

为什么BeautifulSoup无法在Python的表中找到文本?

[英]Why won't BeautifulSoup find text in a table in Python?

我正在尝试检查是否在表中找到了数值。 为什么此代码在此表中找不到数字文本“ 699”? 打印语句的值为“无”。

html = """

<table>
December 31,                            1997     1996     1995     1994     1993
Allowance for credit losses--loans       699      773
Allowance for credit losses--
  trading assets                         285      190
Allowance for credit losses--
  other liabilities                       13       10
- --------------------------------------------------------------------------------
   Total                              $  997   $  973   $  992   $1,252   $1,324
================================================================================
</table>

"""

soup = BeautifulSoup(''.join(html))
table = soup.find('table')
test = table.find(text='699')
print test

table.find()将搜索表内的所有标签,但表内没有标签。 只有一个字符串,它恰好是一个ASCII表,绝不格式化为HTML。

如果要使用BeautifulSoup解析表,则需要先将其转换为HTML表。 否则,您可以使用table.string获取字符串本身,并使用正则表达式进行解析。

如果将字符串作为参数传递给Beautiful Soup find()方法 ,则Beautiful Soup将查找该确切的字符串。 传递text ='699'将找到字符串“ 699”,但找不到包含“ 699”的更长字符串。

要查找包含子字符串的字符串,可以使用自定义函数或正则表达式:

 import re
 table.find(text=re.compile('699')
 table.find(text=lambda x: '699' in x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM