python - 如果包含某些单词,则提取 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>
解决方案
使用 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']
推荐阅读
- jmeter - 仅使用一个凭证进行负载测试
- html - 使输入和跨度彼此相邻
- java - 删除所有点,但不删除 \in 数字 - Java
- json - 在问题之间共享数据——不能为第二个业务产生不同的结果
- c# - 我想要它,所以当我单击下拉选项并单击文本时,图像旁边会出现一个图像
- javascript - 检查经纬度列表是否在范围内
- python - Airflow - 使用 COPY 导出 PostgreSQL 表
- react-native - 如何仅渲染数组中的第一个对象?React Native 扁平列表
- python - 简化 Python 中的条件语句
- python - Python嵌套for循环排序