我正在尝试从下面的html源代码中获取标签列表,这些标签是,CTC_3D_Printer,ctc_prusa_i3_pro_b,CTC_Upgrades
html = """
<div class="content_stack">
<h2 class="section-header justify">
Tags
</h2>
<div class="thing-detail-tags-container">
<div class="taglist">
<a href="/tag:CTC_3D_Printer">CTC_3D_Printer</a>
<a href="/tag:ctc_prusa_i3_pro_b">ctc_prusa_i3_pro_b</a>
<a href="/tag:CTC_Upgrades">CTC_Upgrades</a>
</div>
</div>
</div>
<div class="content_stack">
<h2 class="section-header">
Design Tools
</h2>
<div class="taglist">
<span>Tinkercad</span>
</div>
</div>
"""
通常我会使用:
tags = soup.find("h2", string = "Tags").findNextSibling()
去拿标签。但是,由于标签周围有额外的空格,我无法使用它。标签并不总是紧跟在<div class="content_stack">
之后的第一个元素。我如何通过将"find“与一些预定义的函数相结合来解决我的问题?
发布于 2018-06-05 05:00:19
正如文档中的Kinds of filters所解释的那样,您只需编写一个函数(该函数接受一个BS标记对象,如果匹配则返回true ),并将其传递给find
。
他们的示例是一个函数,该函数仅查找具有class
但没有id
的标签
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
对于您的情况,您只需要对文本执行in
检查:
h2 = soup.find('h2', string=lambda s: 'Tags' in s)
…或者:
h2 = soup.find(lambda tag: tag.name=='h2' and 'Tags' in tag.string)
https://stackoverflow.com/questions/50688602
复制相似问题