Beautifulsoup multiple class selector

前端 未结 5 1969
青春惊慌失措
青春惊慌失措 2020-12-05 07:20

I want to select all the divs which have BOTH A and B as class attributes.

The following selection

soup.findAll(\'div\', class_=[\'A\', \'B\'])
         


        
5条回答
  •  猫巷女王i
    2020-12-05 08:08

    You can use CSS selectors instead, which is probably the best solution here.

    soup.select("div.classname1.classname2")
    

    You could also use a function.

    def interesting_tags(tag):
        if tag.name == "div":
            classes = tag.get("class", [])
            return "A" in classes and "B" in classes
    
    soup.find_all(interesting_tags)
    

提交回复
热议问题