Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python soap4 how to find inline style from find_all()

I am attempting to get the height value of an inline style element using python and BeautifulSoup i manage to get all div with a specific class but cannot figure out how to get the inline style=height value of the output below is my code so far.

import requests
from bs4 import BeautifulSoup

URL = "https://exampleonly.org/"
page = requests.get(URL)

soup = BeautifulSoup(page.content, "html.parser")
samples = soup.find_all("div", {"class": "example"})

for sample in samples:
    print(sample)

and my output is below

<div class="example" style="height: 50%;"></div>
<div class="example" style="height: 20%;"></div>
<div class="example" style="height: 40%;"></div>
 

Now what i want to get is the 50%,20% and 40% values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine class and attribute selectors to target elements, then extract the style attribute. Use re to extract the desired values:

from bs4 import BeautifulSoup as bs
import re

html = '''
<div class="example" style="height: 50%;"></div>
<div class="example" style="height: 20%;"></div>
<div class="example" style="height: 40%;"></div>
'''
soup = bs(html, 'lxml')

for i in soup.select('.example[style*=height]'):
    print(re.search(r'(\d+%)', i['style']).group(1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading