BigD
BigD

Reputation: 77

[Python3x]: How to extract two values separately (beautifulsoup)?

This is the value (coordinates) that I would like to have separately (latitude, longitude).

<input id="dokad" value="51.819544, 19.30441" type="hidden">

When I do like that:

lat_lon = soup.find('input', attrs={'id':'dokad'}).get('value')

Result:

lat_lon
Out[1012]: '51.186147, 19.199997'
type(lat_lon)
Out[1013]: str

How can I extract these two values separately?

Upvotes: 1

Views: 69

Answers (2)

MITHU
MITHU

Reputation: 164

Another attempt can be something like below to get them separately:

content='''
<input id="dokad" value="51.819544, 19.30441" type="hidden">
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(content,"lxml")

item = soup.select("#dokad")[0]['value']
lat = item.split(", ")[0]
lon = item.split(", ")[1]

print("Lat: {}\nLong: {}".format(lat,lon))

Result:

Lat: 51.819544
Long: 19.30441

Upvotes: 1

Lycopersicum
Lycopersicum

Reputation: 569

Use str.split() to split string and then float() to convert your strings to float:

  1. lat_lon = lat_lon.split(', ')
  2. And then convert your list elements to float by doing this: lat_lon = [float(number) for number in lat_lon]

now lat_lon variable should contain list of floating point values: [51.186147, 19.199997]

Upvotes: 2

Related Questions