How to Beautiful Soup (bs4) match just one, and only one, css class

后端 未结 7 628
说谎
说谎 2020-12-10 20:28

I am using following code to match all div that have CSS class \"ad_item\".

soup.find_all(\'div\',class_=\"ad_item\")

problem that I have i

7条回答
  •  执笔经年
    2020-12-10 20:34

    You can always write a Python function that matches the tag you want, and pass that function into find_all():

    def match(tag):
        return (
            tag.name == 'div'
            and 'ad_item' in tag.get('class')
            and 'ad_ex_item' not in tag.get('class'))
    
    soup.find_all(match)
    

提交回复
热议问题