【问题标题】:How to find tags with certain children attributes? - BeautifulSoup 4如何找到具有某些子属性的标签? - 美丽汤 4
【发布时间】:2016-06-30 16:19:33
【问题描述】:

我是 Python 和 BeautifulSoup 的新手,我将如何搜索其子项具有某些属性的某些标签? 例如,

<section ...>
<a href="URL" ...>
<h4 itemprop="name">ABC</h4>
<p class="open"></p>
</a>
</section>

如果 class="open",我希望我能获得所有名称 ('ABC') 和 urls("URL")。我可以通过

获取所有部分
soup.findAll(lambda tag: tag.name="section")

但我不知道如何添加其他条件,因为 tag.children 是一个列表迭代器。

【问题讨论】:

    标签: python-2.7 beautifulsoup


    【解决方案1】:

    因为您正在寻找带有&lt;p&gt; 标签的某些属性,所以我将只搜索带有attrs={"class": "open"}&lt;p&gt; 标签,然后选择父标签(即&lt;a&gt; 标签)并收集其余的从中得到的信息。

    soup = BeautifulSoup(data, "html.parser")
    items = soup.find_all("p", attrs={"class": "open"})
    for item in items:
        name = item.parent.h4.text
        url = item.parent.attrs.get('href', None)
        print("{} : {}".format(name, url))
    

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2018-07-18
      • 2020-08-17
      • 2020-06-25
      • 1970-01-01
      相关资源
      最近更新 更多