如何找到具有某些子属性的标签? - BeautifulSoup 4

时间:2016-06-30 16:19:34

标签: python-2.7 beautifulsoup

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

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

我希望如果我能得到所有的名字(&#39; ABC&#39;)和网址(&#34;网址&#34;),如果class =&#34;打开&#34;。我可以通过

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

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

1 个答案:

答案 0 :(得分:1)

由于您正在查找包含<p>代码的特定属性,因此我会仅使用<p>搜索attrs={"class": "open"}个代码,然后选择父代(<a> })并从中收集其余的信息。

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))
相关问题