python - BeautifulSoup : searching for a nested pattern?

标签 python beautifulsoup

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/

相关文章:

python - Python系统的基准测试系统性能

python - 从 Pandas 数据帧生成相似度矩阵

python - 如何在Beautiful Soup中找到所有段落中的所有链接

python - django.db.backends.mysql 的 pymysql3 等价物是什么

python - SpaCy - ValueError : operands could not be broadcast together with shapes (1, 2) (1,5)

python - 构建 RESTFul C++ api 以与 Python 交互

python - 找到标签内容后出现问题,无法求和

javascript - 使用 BeautifulSoup 抓取包含 JavaScript 的网页

python - 无法将 HTML 从网站正确转换为文本

python - 使用 beautifulsoup4 从 html 表中提取值(第 2 行开始,第 1 和第 6 列)