soup.find_all
将在 BeautifulSoup 文档中搜索所有出现的单个标签。有没有办法搜索嵌套标签的特定模式?
例如,我想搜索所有出现的这种模式:
<div class="separator">
<a>
<img />
</a>
</div>
最佳答案
有多种方法可以找到模式,但最简单的方法是使用 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
child ,或在a
里面tag 除了img
还有别的东西标签。如果是这种情况,可以通过额外的检查来改进解决方案(如果需要,将编辑答案)。
关于python - BeautifulSoup : searching for a nested pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23837056/