【发布时间】:2018-07-05 11:09:23
【问题描述】:
我在 HTML 中有两组不同的 div 标签:
<div class="ABC BCD CDE123">
<div class="ABC BCD CDE234">
<div class="ABC BCD CDE345">
和
<div class="ABC XYZ BCD">
我想选择所有带有 ABC 和 BCD 的标签,但不包含带有 BeautifullSoup4 的 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 函数失败的原因。
任何线索我可以根据我的要求过滤标签:
我想选择所有带有 ABC 和 BCD 的标签,但不包含带有 BeautifullSoup4 的 XYZ 类。
【问题讨论】:
-
我当然可以用一些丑陋的多线黑客自己解决这个问题,但我在这里寻找一个好的和干净的解决方案。
-
Lxml + cssselect 可以让你这样做:
.ABC.BCD:not(.XYZ)- 不过我不确定 BS4。
标签: python html beautifulsoup