How to find all divs who's class starts with a string in BeautifulSoup?

后端 未结 2 408
攒了一身酷
攒了一身酷 2020-12-11 00:40

In BeautifulSoup, if I want to find all div\'s where whose class is span3, I\'d just do:

result = soup.findAll(\"div\",{\"class\":\"span3\"})
相关标签:
2条回答
  • 2020-12-11 01:15

    Well, these are id attributes you are showing:

    <div id="span3 span49">
    <div id="span3 span39">
    

    In this case, you can use:

    soup.find_all("div", id=lambda value: value and value.startswith("span3"))
    

    Or:

    soup.find_all("div", id=re.compile("^span3"))
    

    If this was just a typo, and you actually have class attributes start with span3, and your really need to check the class to start with span3, you can use the "starts-with" CSS selector:

    soup.select("div[class^=span3]")
    

    This is because you cannot check the class attribute the same way you checked the id attribute because class is special, it is a multi-valued attribute.

    0 讨论(0)
  • 2020-12-11 01:42

    This works too:

    soup.select("div[class*=span3]") # with *= means: contains
    
    0 讨论(0)
提交回复
热议问题