BeautifulSoup,递归地使用字符串参数解决标记

时间:2016-03-26 20:56:10

标签: beautifulsoup python-3.5

假设我的XML如下:

<a>
    <b>Some</b>
    <c>Content</c>
    <d>Here</d>
</a>
<a>
    <b>Some2</b>
    <c>Content</c>
    <d>Here</d>
</a>
<a>
    <b>Some3</b>
    <c>Content</c>
    <d>Here</d>
</a>

我很幸运能够通过b访问所有soup.find_all("b")代码。但是,我需要递归地指定它,比如说b tag which is child of a tag。我必须充分解决。我试过以下的事情:

soup.find_all("a").find_all("b")
# raises: 'ResultSet' object has no attribute 'find_all'

soup("a")("b")
# raises: 'ResultSet' object is not callable

如何完全处理标签?我必须通过给出字符串类型参数来做到这一点。我不想要一个如下方法:

soup.a.b

环境

  • python 3.5.1
  • beautifulsoup 4.4.1

1 个答案:

答案 0 :(得分:2)

例如,您可以使用CSS选择器选择<b>的直接子项<a>元素:

>>> soup.select("a > b")
[<b>Some</b>, <b>Some2</b>, <b>Some3</b>]