Beautiful Soup:如何搜索嵌套模式?
soup.find_all
是用来在一个 BeautifulSoup 文档中查找所有某个标签的出现次数的。有没有办法可以查找特定的嵌套标签模式呢?
举个例子,我想查找所有这种模式的出现:
<div class="separator">
<a>
<img />
</a>
</div>
2 个回答
1
看看这个文档的部分。你可能需要一个像这样的函数:
def nested_img(div):
child = div.contents[0]
return child.name == "a" and child.contents[0].name == "img"
soup.find_all("div", nested_img)
附言:这个还没有经过测试。
1
有很多方法可以找到这个模式,但最简单的方法是使用CSS选择器
:
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
标签,这个解决方案就不适用了。如果是这种情况,可以通过增加一些检查来改进这个解决方案(如果需要的话我会编辑答案)。