如果html表格中包含某些单词,则提取该表格中的文本

2024-05-20 21:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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>之间的部分。我知道命令检索,但不知道如何将其与if语句组合。你知道吗

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

Tags: 文件字符串文档文本命令pyhtonishtml
2条回答

使用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']

所以一个想法是通过BeautifulSoup获取html。然后您可以简单地访问如下标记:

row = soup.find('tr') # Extract and return first occurrence of tr
print(row)            # Print row with HTML formatting
print("=========Text Result==========")
print(row.get_text()) # Print row as text

然后您可以得到innerHtml并将其与字符串进行比较。这将假定您可以使用BeautifulSoup访问html。从https://www.pluralsight.com/guides/web-scraping-with-beautiful-soup得到这个

相关问题 更多 >