在这些情况下,您正在寻找下一个元素:
for elem in test.find_all(class_="photo"):
print elem.next_sibling
去父母会工作,但然后寻找.stripped_strings
属性代替:
for elem in test.find_all(class_="photo"):
print ' '.join(elem.parent.stripped_strings)
示范:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <div> <img class="photo" /> text1 </div>
... <div> <img class="photo" /> text2 </div>
... ''')
>>> for elem in soup.find_all(class_="photo"):
... print elem.next_sibling
...
text1
text2
>>> for elem in soup.find_all(class_="photo"):
... print ' '.join(elem.parent.stripped_strings)
...
text1
text2