【问题标题】:BeautifulSoup, Recursively Address A Tag with String ArgumentBeautifulSoup,使用字符串参数递归寻址标签
【发布时间】:2016-07-14 10:33:06
【问题描述】:

假设我的 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

【问题讨论】:

    标签: beautifulsoup python-3.5


    【解决方案1】:

    您可以使用 CSS 选择器,例如,选择作为 &lt;a&gt; 的直接子元素的 &lt;b&gt; 元素:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多