Python BeautifulSoup findAll 通过“class”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19969056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:07:23  来源:igfitidea点击:

Python BeautifulSoup findAll by "class" attribute

pythonweb-scrapingbeautifulsoup

提问by appleLover

I want to do the following code, which is what BS documentation says to do, the only problem is that the word "class" isn't just a word. It can be found inside HTML, but it's also a python keyword which causes this code to throw an error.

我想做下面的代码,这是 BS 文档所说的,唯一的问题是“类”这个词不仅仅是一个词。它可以在 HTML 中找到,但它也是一个导致此代码抛出错误的 python 关键字。

So how do I do the following?

那么我该怎么做呢?

soup.findAll('ul', class="score")

回答by aIKid

Here is how to do it:

这是如何做到的:

soup.find_all('ul', {'class':"score"})

回答by mattexx

Your problem seems to be that you expect find_allin the soup to find an exact match for your string. In fact:

您的问题似乎是您希望find_all在汤中找到与您的字符串完全匹配的字符串。事实上

When you search for a tag that matches a certain CSS class, you're matching against any of its CSS classes:

当您搜索与某个 CSS 类匹配的标签时,您将匹配其任何 CSS 类:

You can properly search for a class tag as @alKid said. You can also search with the class_keyword arg.

您可以像@alKid 所说的那样正确搜索类标签。您还可以使用class_关键字 arg 进行搜索。

soup.find_all('ul', class_="score")