BeautifulSoup,在不使用 find_all() 的情况下找到第 n 个 table
BeautifulSoup, finding the nth table without using find_all()
我想使用 BeautifulSoup 找到第 n 个 table。到目前为止,这一直在为我完成工作。
table = soup.find_all('table',{'class':'wikitable sortable jquery-tablesorter'})[nth]
但是如果我确定它是第 n 个 table,其中 n 是我定义的,有没有办法避免搜索并保存所有以前的 table?我觉得如果有一种方法只获取第 n 个 table,我的代码会 运行 快得多。 table 来自维基百科。
使用 .select
和 nth-of-type
。我不确定这是否会使您的代码 运行 更快,为此请查看文档的 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。但是如果你知道表的父 class,你可以做类似 '.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')
来完成
我想使用 BeautifulSoup 找到第 n 个 table。到目前为止,这一直在为我完成工作。
table = soup.find_all('table',{'class':'wikitable sortable jquery-tablesorter'})[nth]
但是如果我确定它是第 n 个 table,其中 n 是我定义的,有没有办法避免搜索并保存所有以前的 table?我觉得如果有一种方法只获取第 n 个 table,我的代码会 运行 快得多。 table 来自维基百科。
使用 .select
和 nth-of-type
。我不确定这是否会使您的代码 运行 更快,为此请查看文档的 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。但是如果你知道表的父 class,你可以做类似 '.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')