Soup.select,只返回第一个结果

Soup.select, get only first result back

有什么方法可以从 for i soup.select(table) 中获取第一个结果吗?我只想要第一个 table,之后的每个 table 都应该被忽略。代码后跟一个 if 语句:if i.find('th', text = 'Foo'):

TLDR;

正在寻找这样的东西:if i[0].find('th', text = 'Foo'):

一种方法是在第一次迭代后立即break

for i in soup.select('table'):
    if i.find('th', text = 'Foo'):
        ...
    break

另一种是链接方法,如果找不到元素则捕获异常:

try:
    el = soup.select('table')[0].find('th', text='Foo')
except AttributeError, TypeError:
    print('element not found')

注意:soup.select('table')[0]soup.find('table') 给出相同的结果