Beautifulsoup:如何找到其第二个父元素具有确切属性的所有元素?
Beatifulsoup: how to find all elements 2nd parent of which has exact attribute?
我 html 结构如下:
<div class="value_i_need_to_match">
<div>
<a href="..."</a>
<a href="..."</a>
<a href="..."</a>
</div>
</div>
<div class="some_other_value">
<div>
<a href="..."</a>
<a href="..."</a>
<a href="..."</a>
</div>
</div>
我需要提取所有 <a>
元素的二级父元素具有 class 属性,其值与 value_i_need_to_match 匹配。这该怎么做?
我试过了:
soup_post.find_all(
lambda tag: tag.name == "a" and tag.parent.parent.find('div').attrs['class'] is 'value_i_need_to_match'))
和
soup_post.find_all(
lambda tag: tag.name == "a" and tag.findParent('div').attrs["class"] == "value_i_need_to_match"))
我们可以一次性完成 CSS selector:
soup_post.select(".value_i_need_to_match > div > a")
其中>
表示直接的亲子关系。
我 html 结构如下:
<div class="value_i_need_to_match">
<div>
<a href="..."</a>
<a href="..."</a>
<a href="..."</a>
</div>
</div>
<div class="some_other_value">
<div>
<a href="..."</a>
<a href="..."</a>
<a href="..."</a>
</div>
</div>
我需要提取所有 <a>
元素的二级父元素具有 class 属性,其值与 value_i_need_to_match 匹配。这该怎么做?
我试过了:
soup_post.find_all(
lambda tag: tag.name == "a" and tag.parent.parent.find('div').attrs['class'] is 'value_i_need_to_match'))
和
soup_post.find_all(
lambda tag: tag.name == "a" and tag.findParent('div').attrs["class"] == "value_i_need_to_match"))
我们可以一次性完成 CSS selector:
soup_post.select(".value_i_need_to_match > div > a")
其中>
表示直接的亲子关系。