How to find tags with only certain attributes - BeautifulSoup

后端 未结 6 801
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 05:23

How would I, using BeautifulSoup, search for tags containing ONLY the attributes I search for?

For example, I want to find all

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 05:37

    As explained on the BeautifulSoup documentation

    You may use this :

    soup = BeautifulSoup(html)
    results = soup.findAll("td", {"valign" : "top"})
    

    EDIT :

    To return tags that have only the valign="top" attribute, you can check for the length of the tag attrs property :

    from BeautifulSoup import BeautifulSoup
    
    html = '.....\
            .......\
            .....'
    
    soup = BeautifulSoup(html)
    results = soup.findAll("td", {"valign" : "top"})
    
    for result in results :
        if len(result.attrs) == 1 :
            print result
    

    That returns :

    .....
    

提交回复
热议问题