Shyam BHAGAT
Shyam BHAGAT

Reputation: 43

How to I print the value of a tag name rather than the value in Beautiful Soup 4 and Python3?

I am trying to extract the value 86830 from HTML source code using bs4. Here is what I have till now:

page = requests.get("https://www.sunnyportal.com/Templates/PublicPage.aspx?page=1169a2ff-8f51-4ea9-ba72-316009593c62")

soup = BeautifulSoup(page.content, 'html.parser')

Now I try to extract the span id with that value:

pv_current = soup.find("span", attrs = {"class" : "mainValueAmount"})

print(pv_current)

And the output I get is

<span class="mainValueAmount" data-peak="164610" data-timestamp="2020-10-27T10:30:00" data-value="86830">-</span>

My question is, how do I extract this value of 86830? Thanks.

Upvotes: 0

Views: 46

Answers (1)

Sushil
Sushil

Reputation: 5531

data-value is an attribute of the span tag. You have to use square brackets in order to extract the attribute values from a tag. Here is how you do it:

value = pv_current['data-value']

print(value)

Output:

86830

Here is the full code:

from bs4 import BeautifulSoup
import requests

page = requests.get("https://www.sunnyportal.com/Templates/PublicPage.aspx?page=1169a2ff-8f51-4ea9-ba72-316009593c62")

soup = BeautifulSoup(page.content, 'html.parser')

pv_current = soup.find("span", attrs = {"class" : "mainValueAmount"})

value = pv_current['data-value']

print(value)

Upvotes: 1

Related Questions