首页 > 解决方案 > 如果包含某些单词,则提取 html 表中的文本

问题描述

Pyhton 初学者在这里。可能有一个我不知道但在网上找不到解决方案的命令。我的 Python 设置中有一个字符串格式的 html 文件。该文件看起来像

<table>
This is Table 1
</table>

<table>
This is Table 2
</table>

<table>
This is Table 3
</table>

我想提取 和 之间的文本,但前提是它与表中的某些字符串匹配。所以,我只想要表 2 的表。

我尝试在桌子上拆分文档,但这变得很乱,因为它还包括</table> and <table>. 我知道命令 re.search,但不知道如何将它与 if 语句结合使用。

re.search(<table>(.*)</table>

标签: python

解决方案


使用 lxml 解析器来解决这个问题。

from lxml import html

text = '''<table>This is Table 1</table>

<table>This is Table 2</table>

<table>This is Table 3</table>'''

parser = html.fromstring(text)
parser.xpath("//table[contains(text(), 'Table 2')]/text()")

输出将如下所示

['This is Table 2']

推荐阅读