BeautifulSoup,使用字符串参数递归寻址标签
BeautifulSoup, Recursively Address A Tag with String Argument
假设我的 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>
幸运的是,我可以通过 soup.find_all("b")
访问所有 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
您可以使用 CSS select 或者,例如 select <b>
元素,它是 <a>
的直接子元素:
>>> soup.select("a > b")
[<b>Some</b>, <b>Some2</b>, <b>Some3</b>]
假设我的 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>
幸运的是,我可以通过 soup.find_all("b")
访问所有 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
您可以使用 CSS select 或者,例如 select <b>
元素,它是 <a>
的直接子元素:
>>> soup.select("a > b")
[<b>Some</b>, <b>Some2</b>, <b>Some3</b>]