1

In BeautifulSoup you can search by using soup.find_all. For example I searched a page by using

soup.find_all("tr", "cat-list-row1")

That, obviously, brought every tr class that had the name cat-list-row1. I was wanting to know if it is possible to search the whole page for any class that is named "cat-list-row1" instead of limiting it to just classes where the element is "tr".

Scott
  • 471
  • 3
  • 9
  • 19

1 Answers1

6

Multiple ways:

  • using a class_ argument (class cannot be used, it is a reserved keyword in Python):

    soup.find_all(class_="cat-list-row1")
    
  • use attrs dictionary

    soup.find_all(attrs={"class": "cat-list-row1"})
    
  • use a CSS selector:

    soup.select('.cat-list-row1')
    

Note that BeautifulSoup handles multiple classes easily applying the "Multi-valued attributes" concept:

Remember that a single tag can have multiple values for its “class” attribute. When you search for a tag that matches a certain CSS class, you’re matching against any of its CSS classes.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • What if there were multiple classnames for "cat-list-row1" on the page that did not have the "tr" element? Is there a way I could just search for "cat-list-row1"? – Scott Dec 30 '14 at 19:14
  • @Scott please see the update and the appropriate [documentation page](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class). Should clear things up. – alecxe Dec 30 '14 at 19:16
  • Thanks to all of you. I was able to accomplish it with your help. – Scott Dec 30 '14 at 19:22