BeautifulSoup,在不使用find\u all()的情况下查找第n个表

2024-05-12 20:57:12 发布

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

我想用BeautifulSoup找到第n个表。到目前为止,这是我的工作。你知道吗

table = soup.find_all('table',{'class':'wikitable sortable jquery-tablesorter'})[nth]

但是如果我确定它是我定义的第n个表,有没有办法避免搜索和保存所有以前的表呢?我觉得如果有一种方法,只有当表是第n个表时,我的代码才能运行得更快。这些表格来自维基百科。你知道吗


Tags: 方法代码定义tableallfindjqueryclass
1条回答
网友
1楼 · 发布于 2024-05-12 20:57:12

nth-of-type一起使用.select。我不确定这是否会使您的代码运行得更快,为此请查看文档的improving performance部分。你知道吗

from bs4 import BeautifulSoup
html="""
<table class="1">
</table>
<table class="2">
</table>
<table class="3">
</table>
<table class="4">
</table>
<table class="5">
</table>
"""
soup=BeautifulSoup(html,'html.parser')
print(soup.select('table:nth-of-type(3)'))

输出

[<table class="3">
</table>]

css选择器.class:nth-of-type(n)似乎不适用于BeautifulSoup。但是如果您知道表的父类,您可以执行类似于'.parent table:nth-of-type(n)'

from bs4 import BeautifulSoup
html="""
<div class="parent1">
<table class="tbl">
not our table 1
</table>
<table class="tbl">
not out table 2
</table>
</div>
<div class="parent2">
<table class="tbl">
our table 1
</table>
<table class="tbl">
our table 2
</table>
</div>
"""
soup=BeautifulSoup(html,'html.parser')
print(soup.select('.parent2 table:nth-of-type(2)'))

输出

[<table class="tbl">
our table 2
</table>]

上述输出也可以通过soup.select('.parent2 .tbl ~ .tbl')实现

相关问题 更多 >