如何使用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:
1. Use CSS Selectors (Recommended)
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

