Skip to content

Instantly share code, notes, and snippets.

@AO8
Last active December 14, 2018 21:57
Show Gist options
  • Select an option

  • Save AO8/7706cb8c05ea4991fb9e9da8e25ce367 to your computer and use it in GitHub Desktop.

Select an option

Save AO8/7706cb8c05ea4991fb9e9da8e25ce367 to your computer and use it in GitHub Desktop.
Retrieve temperature and weather conditions with this simple Python weather client using Weather Underground, Requests, and BeautifulSoup.
# Screen scraping information from Weather Underground at https://www.wunderground.com/ is for
# example purposes only. Try the Weather Underground API at https://www.wunderground.com/weather/api
# Project adapted from Michael Kennedy's Python Jumpstart by Building 10 Apps course
# Standard Library
from collections import namedtuple
# Third Party
import requests
from bs4 import BeautifulSoup
WeatherReport = namedtuple("WeatherReport", "loc condition temp scale")
def main():
print_header()
code = input("What zip code for you want weather for (98092)? ")
html = get_html_from_web(code)
report = get_weather_from_html(html)
print("The temperature in {} is {}°{}. Conditions are {}.".format(
report.loc,
report.temp,
report.scale,
report.condition.lower()
))
def print_header():
print("--------------------------------------------------------------")
print(" WEATHER APP")
print("--------------------------------------------------------------")
print()
def get_html_from_web(zipcode):
url = "http://www.wunderground.com/weather-forecast/{}".format(zipcode)
response = requests.get(url)
return response.text
def get_weather_from_html(html):
soup = BeautifulSoup(html, "html.parser")
loc = soup.find(class_="city-header").find("h1").get_text()
condition = soup.find(class_="condition-icon").get_text()
temp = soup.find(class_="wu-unit-temperature").find(class_="wu-value").get_text()
scale = soup.find(class_="wu-unit-temperature").find(class_="wu-label").get_text()
loc = cleanup_text(loc)
condition = cleanup_text(condition)
temp = cleanup_text(temp)
scale = cleanup_text(scale)
report = WeatherReport(loc=loc, condition=condition, temp=temp, scale=scale)
return report
def cleanup_text(text: str): # example of type hints
if not text:
return text
text = text.strip()
return text
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment