2

I have this prettify html

         <a href="somepath">
          Text1
         </a>
         <span>
          |
         </span>
         <a href="somepath">
          Text2
         </a>
         <span>
          |
         </span>
         <a href="somepath">
          Text3
         </a>

I used this code:

cnta= len(res.findAll('a'))-1 //I used -1 because I have one extra a tag
cnt = 0
while cnt<cnta:
    res2 = res.find('a').text
    cnt+=1
    print res2

I want to take all 3 Texts but the result is 3 times "Text1"... I know that I not saying anyone to go to next but I don't know how to do it

a1204773
  • 6,923
  • 20
  • 64
  • 94

1 Answers1

2

Just loop directly over the findAll results:

for elem in res.findAll('a'):
    print elem

The .find() method just returns the first element within res it finds, it doesn't continue the search from the last hit you found. So on each run through the loop it'll find the same element.

If you want to limit the number of results, use slice notation:

for elem in res.findAll('a')[:3]:
    print elem
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343