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>
Exactly that, great answer!
– lmonferrari
Understood so the way to search for elements after a find_all is to pass a for
– user201087