How to find elements by class

后端 未结 17 1427
有刺的猬
有刺的猬 2020-11-22 08:33

I\'m having trouble parsing HTML elements with \"class\" attribute using Beautifulsoup. The code looks like this

soup = BeautifulSoup(sdata)
mydivs = soup.fi         


        
相关标签:
17条回答
  • 2020-11-22 08:57

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

    Hence the answer will be

    soup.find_all("html_element", class_="your_class_name")
    
    0 讨论(0)
  • 2020-11-22 08:57

    As of BeautifulSoup 4+ ,

    If you have a single class name , you can just pass the class name as parameter like :

    mydivs = soup.find_all('div', 'class_name')
    

    Or if you have more than one class names , just pass the list of class names as parameter like :

    mydivs = soup.find_all('div', ['class1', 'class2'])
    
    0 讨论(0)
  • 2020-11-22 08:57

    This should work:

    soup = BeautifulSoup(sdata)
    mydivs = soup.findAll('div')
    for div in mydivs: 
        if (div.find(class_ == "stylelistrow"):
            print div
    
    0 讨论(0)
  • 2020-11-22 08:58

    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">
    
    0 讨论(0)
  • 2020-11-22 09:00

    Try to check if the div has a class attribute first, like this:

    soup = BeautifulSoup(sdata)
    mydivs = soup.findAll('div')
    for div in mydivs:
        if "class" in div:
            if (div["class"]=="stylelistrow"):
                print div
    
    0 讨论(0)
  • 2020-11-22 09:09

    the following worked for me

    a_tag = soup.find_all("div",class_='full tabpublist')
    
    0 讨论(0)
提交回复
热议问题