0

I need some help extracting an integer from strings created by beautiful soup. This is the following code I have.

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup

#San Pedro 
url = "http://www.ndbc.noaa.gov/mobile/station.php?station=46222"
r = requests.get(url)

soup = BeautifulSoup(r.content, "html.parser")

g_data = soup.find_all("body")

for item in g_data:
    #Wheater Conditions
       print item.contents[6]

    #Wave Summary 
       print item.contents[9]

I am given the following output.

9:19 pm PST 01-Dec-2015
Seas: 3.9 ft (1.2 m)
Peak Period: 15 sec
Water Temp: 65 °F (18 °C)

9:19 pm PST 01-Dec-2015
Swell: 3.0 ft (0.9 m)
Period: 15.4 sec
Direction: W
Wind Wave: 2.3 ft (0.7 m)
Period: 9.9 sec
Direction: W

HTML Version

 <p>9:19 pm PST 01-Dec-2015<br>
<b>Seas:</b> 3.9 ft (1.2 m)<br>
<b>Peak Period:</b> 15 sec<br>
<b>Water Temp:</b> 65 °F (18 °C)<br>
</br></br></br></br></p>
<p>
9:19 pm PST 01-Dec-2015<br>
<b>Swell:</b> 3.0 ft (0.9 m)<br>
<b>Period:</b> 15.4 sec<br>
<b>Direction:</b> W<br>
<b>Wind Wave:</b> 2.3 ft (0.7 m)<br>
<b>Period:</b> 9.9 sec<br>
<b>Direction:</b> W<br>
</br></br></br></br></br></br></br></p>

I need to get the individual value of each category I.E. make a value as such swell = 3.0

Thanks

2 Answers2

0

Not sur this is the best solution but something like this should do :

def extractInt(string) :
    stringToReturn = ""
    for x in string :
        if x.isdigit() or x==" " :
            stringToReturn = stringToReturn + x
    return stringToReturn

Just call this function on the string you want.

Amr El Aswar
  • 3,395
  • 3
  • 23
  • 36
0

If you want to have numbers with floating points, you want to have floats intead of integers. To simply get number from string do:

if your_string.isdigit():
    your_float = float(your_string)
PatNowak
  • 5,721
  • 1
  • 25
  • 31