我正在尝试使用 Beautiful Soup 来搜索 html 文档。有没有办法在文档中搜索包含某些关键字字符串的表格?例如,如果我有 table :
<table>
<tr>
<td> 'abc' </td>
<td> 'other data' </td>
</tr>
<tr>
<td> 'def' </td>
<td> 'other data' </td>
</tr>
<tr>
<td> '123' </td>
<td> 'other data' </td>
</tr>
<tr>
<td> '456' </td>
<td> 'other data' </td>
</tr>
</table>
在一个包含许多其他表格的 html 文档中,但这是唯一包含字符串“abc”、“def”和“456”的表格,有没有办法搜索此表格?
我的一个想法是使用 for 循环来搜索所有表、行和数据,但这似乎是不必要的步骤(文档非常大)。有没有一种方法可以使用 BeautifulSoup 来形成问题,比如(显然这行不通,但也许它让我知道我想写什么):
.find('table', string=('abc'), string=('def'), string=re.compile('456'))
编辑:是的,表格需要所有这些字符串。 html 文件还包含其他表格,这些表格可能包含任何这些字符串,但只有 1 个表格包含所有 3 个字符串。是的,我只会在标签中寻找字符串(可能是“文本”而不是“字符串”,我不确定其中的区别)。
请您参考如下方法:
一个解决方案是将 pass a function 转换为 soup.find() 。该函数必须接受一个且仅一个参数(一个 bs4.element.Tag 对象),其目的是仅返回 True 或 False:如果表格符合您设定的条件则为 True。
如果你想测试不同的字符串,你可以从一个带有两个参数的函数开始,然后使用 functools.partial() 将它减少到一个:
from functools import partial
def _table_contains_strs(tag, strings):
"""Return True if `tag` has <td> tags that contain `strings`."""
if tag.name != 'table':
return False
tds = tag.find_all('td')
if not tds:
return False
test = {s: False for s in strings}
for tag in tds:
for s in strings:
if s in tag:
test[s] = True
if all(test.values()):
# You can return early (without full iteration)
# if all strings already matched.
return True
return False
def _make_single_arg_function(func, *args, **kwargs):
return partial(_table_contains_strs, *args, **kwargs)
table_contains_strs = _make_single_arg_function(
_table_contains_strs,
strings=('abc', 'def', '456')
)
现在 table_contains_strs 是一个接受单个参数的函数,一个 Tag 。
这是一个例子:
from bs4 import BeautifulSoup
# Add some text to other tags to make sure you're
# finding only in <td>s
html = """\
<table>
<th>field1</th>
<th>field2</th>
<tr>
<td>abc</td>
<td>other data</td>
</tr>
<tr>
<td>def</td>
<td>other data</td>
</tr>
<tr>
<td>123</td>
<td>other data</td>
</tr>
<tr>
<td>456</td>
<td>other data</td>
</tr>
</table>"""
soup = BeautifulSoup(html, 'html.parser')
soup.find(table_contains_strs)
# Should return the table above
注意:我不能说这会非常好地扩展,因为它使用嵌套的 for 循环来检查 each <td> 标记中的 each 字符串。但希望它能完成工作。只使用 .text 可能不是一个好主意,因为这也会捕获其他嵌套标签,而您指定不需要这些标签。另一个优化是制作 find_all() 的惰性 generator version。
