The Python Oracle

How to find elements by class

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
00:42 Accepted answer (Score 984)
00:59 Answer 2 (Score 413)
01:29 Answer 3 (Score 79)
01:51 Answer 4 (Score 46)
04:49 Thank you

--

Full question
https://stackoverflow.com/questions/5041...

Answer 1 links:
[As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument]: https://www.crummy.com/software/Beautifu...

Answer 2 links:
[Link to official documentation]: https://www.crummy.com/software/Beautifu...
[image]: https://i.stack.imgur.com/cMifn.png

Answer 3 links:
[soupsieve 2.1.0 + Dec'2020 onwards]: https://github.com/facelessuser/soupsiev...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #html #webscraping #beautifulsoup

#avk47



ACCEPTED ANSWER

Score 1069


You can refine your search to only find those divs with a given class using BS3:

mydivs = soup.find_all("div", {"class": "stylelistrow"})



ANSWER 2

Score 447


From the documentation:

As of Beautiful Soup 4.1.2, you can search by CSS class using the keyword argument class_:

soup.find_all("a", class_="sister")

Which in this case would be:

soup.find_all("div", class_="stylelistrow")

It would also work for:

soup.find_all("div", class_="stylelistrowone stylelistrowtwo")



ANSWER 3

Score 82


Update: 2016 In the latest version of beautifulsoup, the method 'findAll' has been renamed to 'find_all'. Link to official documentation

List of method names changed

Hence the answer will be

soup.find_all("html_element", class_="your_class_name")



ANSWER 4

Score 24


Specific to BeautifulSoup 3:

soup.findAll('div',
             {'class': lambda x: x 
                       and 'stylelistrow' in x.split()
             }
            )

Will find all of these:

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">