Parse html comments inside <style> tag using BeautifulSoup

<style type="text/css">
<!--
    p {margin: 0; padding: 0;}  .ft10{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#ffffff;}
    .ft11{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#105334;-moz-transform: matrix(         0,          1,         -1,          0, 0, 0);-webkit-transform: matrix(         0,          1,         -1,          0, 0, 0);-o-transform: matrix(         0,          1,         -1,          0, 0, 0);-ms-transform: matrix(         0,          1,         -1,          0, 0, 0);-moz-transform-origin: left 75%;-webkit-transform-origin: left 75%;-o-transform-origin: left 75%;-ms-transform-origin: left 75%;}
-->
</style>

I want to extract the attributes of .ft10 and .ft11 from above html snippet.

I'm using Comment function from bs4 but it returns an empty list.

for style in soup.find_all('style'):

        comments = style.find_all(string=lambda text: isinstance(text, Comment))
        print("comments ====> ", comments)
        for c in comments:
            print(c)
            print("===========")
            c.extract()

I want a list consisting of font-size, family and color from all classes.

Upvotes: 1

Views: 1154

Answers (1)

KunduK
KunduK

Reputation: 33384

I am able to fetch the value.However not sure this will work other Use-cases as well.

from bs4 import BeautifulSoup
from bs4 import Comment
html='''<style type="text/css"> <!-- p {margin: 0; padding: 0;} .ft10{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#ffffff;} .ft11{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#105334} --> </style> '''
soup=BeautifulSoup(html,'html.parser')
item=soup.find('style')
data1=item.next_element
soup1=BeautifulSoup(data1,'html.parser')
comments = soup1.find_all(string=lambda text: isinstance(text, Comment))
for c in comments:
  data=c.strip().split('}')
  str1=data[1].split('.ft10')[1]+ "}"
  str2=data[2].split('.ft11')[1]+ "}"

print(str1)
print(str2)

Output:

{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#ffffff;}
{font-size:17px;font-family:JEFJLV+FoundersGrotesk-Medium;color:#105334}

Upvotes: 1

Related Questions