2

I want to extract a div using its style property padding-left: 16px, something like shown in the following Python code. But apparently it doesn't work. I know how to extract an element using its class, id or tags. Is there a way to do the same using style property?

from bs4 import BeautifulSoup

f = open("C:\Users\admin\Documents\GitHub\RedditCrawler\new.html");
soup = BeautifulSoup(f);
f.close();

hr2 = soup.find('div', style={"padding-left":"16px"});

print(hr2);

Following is the div I'm trying to extract from my html file:

<html>
<div style="padding-left:16px;">This is the deal</div>
</html>
Sacha
  • 819
  • 9
  • 27
GrozaFry
  • 41
  • 7
  • 2
    one of these should work https://stackoverflow.com/a/23584775/1289093 https://stackoverflow.com/a/35140202/1289093 – yolabingo Dec 23 '19 at 22:39
  • @yolabingo Thank You for the quick reply. The first link worked for me. It is strange though that I couldn't find the already answered similar question even though I had been searching here for quite a while. – GrozaFry Dec 23 '19 at 22:50

1 Answers1

2

Use CSS selector to get the div element.

soup.select_one('div[style="padding-left:16px;"]')

Code:

from bs4 import BeautifulSoup
html='''<html>
<div style="padding-left:16px;">This is the deal</div>
</html>'''
soup=BeautifulSoup(html,'html.parser')
#To get the element
print(soup.select_one('div[style="padding-left:16px;"]'))
#To get the text
print(soup.select_one('div[style="padding-left:16px;"]').text)
#To get the style value
print(soup.select_one('div[style="padding-left:16px;"]')['style'])

Output:

<div style="padding-left:16px;">This is the deal</div>
This is the deal
padding-left:16px;
KunduK
  • 32,888
  • 5
  • 17
  • 41