首先,可以检查在查找时是否正确指定了类名。其次,如果类名是动态添加的,则可以考虑使用正则表达式或lambda函数来查找。以下是一个使用正则表达式查找类名的示例代码:
import re
from bs4 import BeautifulSoup
html = """
This is content 1.
This is content 2.
"""
soup = BeautifulSoup(html, 'html.parser')
containers = soup.find_all('div', {'class': re.compile(r'\bcontainer\b')})
print(len(containers)) # 输出 2
此代码中,使用了re.compile函数来创建一个正则表达式,用于匹配所有包含“container”的类名。然后,使用find_all方法查找所有具有此特定类名的容器。
如果要使用lambda函数,则可以使用以下示例代码:
from bs4 import BeautifulSoup
html = """
This is content 1.
This is content 2.
"""
soup = BeautifulSoup(html, 'html.parser')
containers = soup.find_all(lambda tag: tag.name == 'div' and 'container' in tag.get('class', []))
print(len(containers)) # 输出 2
其中,使用lambda函数来判断标签是否为div,并且是否具有包含“container”的类名。
上一篇:Beautifulsoup的find_all方法无法找到没有data_reactid属性的元素。
下一篇:BeautifulSoup的find_all方法中能否使用lambda函数来过滤出符合条件的元素?是否还有其他方法可以实现类似的筛选效果?