美丽的汤:寻找嵌套模式?

Mar*_*son 5 python beautifulsoup

soup.find_all将在BeautifulSoup文档中搜索所有出现的单个标记.有没有办法搜索嵌套标签的特定模式?

例如,我想搜索此模式的所有实例:

<div class="separator">
  <a>
    <img />
  </a>
</div>
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 1

有多种方法可以找到模式,但最简单的方法是使用CSS selector

for img in soup.select('div.separator > a > img'):
    print img  # or img.parent.parent to get the "div"
Run Code Online (Sandbox Code Playgroud)

演示:

>>> from bs4 import BeautifulSoup
>>> data = """
... <div>
...     <div class="separator">
...       <a>
...         <img src="test1"/>
...       </a>
...     </div>
... 
...     <div class="separator">
...       <a>
...         <img src="test2"/>
...       </a>
...     </div>
... 
...     <div>test3</div>
... 
...     <div>
...         <a>test4</a>
...     </div>
... </div>
... """
>>> soup = BeautifulSoup(data)
>>> 
>>> for img in soup.select('div.separator > a > img'):
...     print img.get('src')
... 
test1
test2
Run Code Online (Sandbox Code Playgroud)

我确实明白,严格来说,如果div有多个子a项,或者a标签内有除标签之外的其他内容,则该解决方案将不起作用img。如果是这种情况,可以通过额外检查来改进解决方案(如果需要,将编辑答案)。