0
<div> <img class="photo" /> text1 </div>
<div> <img class="photo" /> text2 </div>

试图获取 text1,text2。我尝试这样的事情,但它失败了,

for i in test.find_all(class_="photo"):
     print i.parent[1]

错误:

RuntimeError: maximum recursion depth exceeded

知道为什么吗?

4

1 回答 1

1

在这些情况下,您正在寻找下一个元素:

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
于 2013-03-22T12:39:48.850 回答