Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML with BS4

How would I go about getting the value under the tag declination units? I'm looking to return the '-6.43798' using BeautifulSoup4 in python.

<html><body><maggridresult>
<version>
0.5.0.7
</version>
<result>
<date>
2017.07671
</date>
<latitude units="degree">
42.26042
</latitude>
<longitude units="degree">
-84.46044
</longitude>
<elevation units="km">
0.00000
</elevation>
<declination units="degree">
-6.43798
</declination>
<declination_sv units="degree">
-0.03752
</declination_sv>
<declination_uncertainty units="degree">
0.37303
</declination_uncertainty>
</result>
</maggridresult>
</body></html>

I think it has to do with the find or find all function but I'm not sure how in specific to implement it.

Thanks!


1 Answers

import bs4
html = """your html"""

soup = bs4.BeautifulSoup(html, 'lxml')
soup.find('declination').get_text(strip=True) # strip white-space 

out:

'-6.43798'

find use tag name and tag attribute as filter.

like image 174
宏杰李 Avatar answered Oct 20 '25 17:10

宏杰李