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

时间:2014-05-23 19:26:15

标签: python beautifulsoup

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

例如,我想搜索所有这种模式:

<div class="separator">
  <a>
    <img />
  </a>
</div>

2 个答案:

答案 0 :(得分:1)

查看docs的这一部分。你可能想要这样的函数:

def nested_img(div):
    child = div.contents[0]
    return child.name == "a" and child.contents[0].name == "img"

soup.find_all("div", nested_img)

P.S。:这是未经测试的。

答案 1 :(得分:1)

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

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

演示:

>>> 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

我确实理解,严格来说,如果div只有一个a子项,或者a标记内部除了img标记。如果是这种情况,可以通过额外的检查来改进解决方案(如果需要,将编辑答案)。

相关问题