Bob Wassermann
Bob Wassermann

Reputation: 369

Soup.select, get only first result back

Is there any way to just get the first result back from for i soup.select(table)? I just want the first table, every table after it should be ignored. The code is followed by an if statement: if i.find('th', text = 'Foo'):

TLDR;

Looking for something like this: if i[0].find('th', text = 'Foo'):

Upvotes: 4

Views: 4866

Answers (1)

fferri
fferri

Reputation: 18950

One way is to break right after the first iteration:

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

Another one is to chain methods, and catch exception if element not found:

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

Note: soup.select('table')[0] and soup.find('table') give the same result

Upvotes: 3

Related Questions