我正在HTML中使用两个不同的div标签:
<div class="ABC BCD CDE123">
<div class="ABC BCD CDE234">
<div class="ABC BCD CDE345">
and
<div class="ABC XYZ BCD">
我希望使用BeautifulSoup4选择所有包含ABC和BCD标签的内容,但不包括XYZ类。
我已经了解到以下方法:
soup.find_all('div', class_=['ABC','BCD'])
搜索时使用OR
(因此必须存在ABC或BCD)。
我也知道这里的方法:
def myfunction(theclass):
return theclass is not None and len(theclass)=5
soup.find_all('div', class_=myfunction)
这将返回所有类名长度为5的div元素。
然后我尝试使用以下方法解决我的问题:
soup.find_all('div', class_ = lambda x: x and 'ABC' and 'BCD' in x.split() and x and 'XYZ' not in x.split())
但是这并没有起作用。 因此,我尝试使用以下方法进行调试:
def myfunction(theclass):
print theclass
return True
soup.find_all('div', class_=myfunction)
问题似乎是从这样的标签开始的:
这个标签看起来像是:
<div class="ABC BCD CDE123">
只有“ABC”被传递给
myfunction
,因此theclass = 'ABC'
而不是我预期的theclass ='ABC BCD CDE123'
。这也是我猜测lambda函数失败的原因。有什么线索可以根据我的要求过滤标签吗?
我想使用BeautifullSoup4选择所有包含ABC和BCD的标签,但不包含XYZ类。
.ABC.BCD:not(.XYZ)
- 不过我不确定 BS4 是否支持。 - pguardiario