Contents of Attribute - BeautifulSoup

Viewed 79

I am trying to pick up the price attribute in the below html:

<html><body><p>[<meta content="60.00" itemprop="price"/>]</p></body></html>

I am using the beautifulsoup library in python3.

Below is my current code. However i have tried many iterations of things using the docs.

soup = bs4.BeautifulSoup(res.text, 'lxml')
soup = bs4.BeautifulSoup(str(price), 'lxml')
for element in soup.find_all():
            print(element ["content"])

Currently the above code just prints out the same html line again.

The result i am trying to achieve is using the 'content' attribute, which isn't always 'content' but in this case it is, and retrieving the value of 60.00.

Any help would be appreciated.

Thanks!

2 Answers

You can try it.

from bs4 import BeautifulSoup
html_doc ="""<html><body><p>[<meta content="60.00" itemprop="price"/>]</p></body></html>"""

soup= BeautifulSoup(html_doc, 'lxml')
price = soup.find("p").meta['content']

print(price)

Output will be:

60.00

since your <meta content="60.00" itemprop="price"/> not containing any other decimal value, you can use this code :)

import re
from bs4 import BeautifulSoup
html = """<html><body><p>[<meta content="60.00" itemprop="price"/>]</p></body></html>"""
soup = BeautifulSoup(html)
x = soup.findAll(name = 'meta')
print(re.sub('[^0-9,.]', '', str(x)))

Output will be : 60.00

Related