How to use find in find_all result

Asked

Viewed 72 times

-1

When I execute a find_all, then I can’t use find in the outcome of this. Example:

anuncios = soup.find_all('div', class_='txt-value')

anuncios.find('p', class_='well') # Erro!

But if I don’t find_all, and instead use find, there works:

anuncios = soup.find('div', class_='txt-value')

anuncios.find('p', class_='well') # não dá erro

1 answer

1

This is because find_all returns a list of elements, but find can only be called from one element.

And how find only returns a single element, that’s why the second code works (the first find search for a div, and from it you make another find).

The detail is that find will return the first element found. In your case, for example, if you have two div's whose class is txt-value, soup.find('div', class_='txt-value') will return the first of them.

Already with find_all you have a list of all the div's, and can search for the p from them:

html = '''
<div id="a1" class="txt-value"><p class="well">bla1</p></div>
<div id="a2" class="txt-value"><p class="well">bla2</p></div>
<div id="a3" class="txt-value"><p class="well">bla3</p></div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')

# buscar todas as div's
for anuncio in soup.find_all('div', class_='txt-value'):
    # para cada div, procuro o "p"
    p = anuncio.find('p', class_='well')
    print('encontrei: ', p)

# procuro somente a primeira div que tenha class-"txt-value"
anuncio = soup.find('div', class_='txt-value')
# dentro desta div procuro o "p"
p = anuncio.find('p', class_='well')
print('p dentro da primeira div:', p)

The exit code above is:

encontrei:  <p class="well">bla1</p>
encontrei:  <p class="well">bla2</p>
encontrei:  <p class="well">bla3</p>
p dentro da primeira div: <p class="well">bla1</p>
  • 1

    Exactly that, great answer!

  • Understood so the way to search for elements after a find_all is to pass a for

Browser other questions tagged

You are not signed in. Login or sign up in order to post.