You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Beautiful Soup查找含多属性类的标签?

How to Find Tags with Multi-Value Class Attributes in Beautiful Soup

Great question! The issue here is that when you see an element with class="class Name", those aren’t a single class name—they’re two separate class names (class and Name) assigned to the element. Your initial approach using soup.find_all('a', class_='class Name') fails because Beautiful Soup is trying to match an element with a single class literally named class Name, which isn’t what your HTML actually has.

Here are two reliable ways to target these elements:

CSS selectors handle multiple class names naturally—just chain them with dots. This will select all <a> tags that have both class and Name classes (the order of classes in the HTML doesn’t matter):

soup.select('a.class.Name')

2. Pass a List to the class_ Parameter

Beautiful Soup accepts a list of class names for the class_ argument. It will match elements that contain all the classes in the list:

soup.find_all('a', class_=['class', 'Name'])

Edge Case: Literal Class Name with Spaces (Rare)

If you actually have an element with a class name that literally includes a space (which goes against HTML best practices but is technically possible), you can use the attrs parameter to match the exact attribute value:

soup.find_all('a', attrs={'class': 'class Name'})

In most real-world scenarios, though, the first two methods are what you’ll need to use.

内容的提问来源于stack exchange,提问作者ElectroMotiveHorse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:11:19