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.
>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))