2024-05-12 20:57:12 发布
网友
我想用BeautifulSoup找到第n个表。到目前为止,这是我的工作。你知道吗
table = soup.find_all('table',{'class':'wikitable sortable jquery-tablesorter'})[nth]
但是如果我确定它是我定义的第n个表,有没有办法避免搜索和保存所有以前的表呢?我觉得如果有一种方法,只有当表是第n个表时,我的代码才能运行得更快。这些表格来自维基百科。你知道吗
与nth-of-type一起使用.select。我不确定这是否会使您的代码运行得更快,为此请查看文档的improving performance部分。你知道吗
nth-of-type
.select
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)'
.class:nth-of-type(n)
'.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')实现
soup.select('.parent2 .tbl ~ .tbl')
与
nth-of-type
一起使用.select
。我不确定这是否会使您的代码运行得更快,为此请查看文档的improving performance部分。你知道吗输出
css选择器
.class:nth-of-type(n)
似乎不适用于BeautifulSoup。但是如果您知道表的父类,您可以执行类似于'.parent table:nth-of-type(n)'
输出
上述输出也可以通过
soup.select('.parent2 .tbl ~ .tbl')
实现相关问题 更多 >
编程相关推荐