如何找到具有特定类名但没有其他类名的 li 标签?例如:
...
<li> no wanted </li>
<li class="a"> not his one </li>
<li class="a z"> neither this one </li>
<li class="b z"> neither this one </li>
<li class="c z"> neither this one </li>
...
<li class="z"> I WANT THIS ONLY ONE</li>
...
代码:
bs4.find_all ('li', class_='z') 返回几个条目,其中有一个 "z" 和另一个类名。
如何单独查找具有类名 "z" 的条目?
请您参考如下方法:
您可以使用 CSS selectors以匹配确切的类名。
html = '''<li> no wanted </li>
<li class="a"> not his one </li>
<li class="a z"> neither this one </li>
<li class="b z"> neither this one </li>
<li class="c z"> neither this one </li>
<li class="z"> I WANT THIS ONLY ONE</li>'''
soup = BeautifulSoup(html, 'lxml')
tags = soup.select('li[class="z"]')
print(tags)
同样的结果可以使用 lambda 实现:
tags = soup.find_all(lambda tag: tag.name == 'li' and tag.get('class') == ['z'])
输出:
[<li class="z"> I WANT THIS ONLY ONE</li>]
看看Multi-valued attributes .您将理解为什么 class_='z' 匹配类名称中包含 z 的所有标签。
HTML 4 defines a few attributes that can have multiple values. HTML 5 removes a couple of them, but defines a few more. The most common multi-valued attribute is
class(that is, a tag can have more than one CSS class). Others includerel,rev,accept-charset,headers, andaccesskey. Beautiful Soup presents the value(s) of a multi-valued attribute as a list:css_soup = BeautifulSoup('<p class="body"></p>') css_soup.p['class'] # ["body"] css_soup = BeautifulSoup('<p class="body strikeout"></p>') css_soup.p['class'] # ["body", "strikeout"]
