• Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

    Mastering python-docx A Guide to Creating Word Documents with Python

    Mastering python-docx: A Guide to Creating Word Documents with Python

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

    10 Tips and Tricks to Secure Your WordPress Website

    10 Tips and Tricks to Securing Your WordPress Website

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support
No Result
View All Result
  • Home
  • Guides
    • All
    • Linux
    • Programming
    • Tools
    • WordPress
    Monitoring Web Page Changes with Python

    Monitoring Web Page Changes with Python

    My SSH Setup: How I Manage Multiple Servers

    My SSH Setup: How I Manage Multiple Servers

    Building a Network Tracker Auditor for Privacy with Python

    Building a Network Tracker Auditor for Privacy with Python

    Streaming Audio Files Securely with PHP

    Streaming Audio Files Securely with PHP

    Scraping Web Data with Python Helium

    Scraping Web Data with Python Helium

    Building a Secure 2FA Authenticator with Python

    Building a Secure 2FA Authenticator with Python

    Building a Cache Warmer with Python

    Building a Cache Warmer with Python

    How to Create a Python GUI to Launch Webhooks

    How to Create a Python GUI to Launch Webhooks

    Mastering python-docx A Guide to Creating Word Documents with Python

    Mastering python-docx: A Guide to Creating Word Documents with Python

  • Blog
    • All
    • Artificial Intelligence
    • Privacy
    • Reviews
    • Security
    • Tutorials
    AdGuard Ad Blocker Review

    AdGuard Ad Blocker Review

    Surfshark VPN Review

    Surfshark VPN Review

    Nmap Unleash the Power of Cybersecurity Scanning

    Nmap: Unleash the Power of Cybersecurity Scanning

    Floorp Browser Review

    Floorp Browser Review

    Understanding Man-in-the-Middle Attacks

    Understanding Man-in-the-Middle Attacks

    Privacy-Focused Analytics

    Privacy-Focused Analytics: Balancing Insights and Integrity

    Safeguarding Your Facebook Account

    Safeguarding Your Facebook Account: Understanding the Differences Between Hacking and Cloning

    38 essential points to harden WordPress

    38 Essential Points to Harden WordPress

    10 Tips and Tricks to Secure Your WordPress Website

    10 Tips and Tricks to Securing Your WordPress Website

  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support
No Result
View All Result
Home Guides Programming Python

Retrieve Weather Data with Python

Jonathan Moore by Jonathan Moore
4 years ago
Reading Time: 2 mins read
A A
Retrieve Weather Data with Python
FacebookTwitter

This simple Python application works similarly to the one we created in Add NWS Weather to Your Website JavaScript guide. This is handy if we need to grab weather data as part of another Python application or if we wanted to use it as the base for a more powerful weather application.

Our Requirements

Before we get started, you will need to install the Requests HTTP library for Python. The Requests library allows us to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to URLs or to form-encode POST data.

pip install requests

Let’s Get Started

As with its JavaScript equivalent, we will be passing the latitude and longitude of the location that we want to retrieve the weather data from to the get_weather function. The data will then be extracted from the JSON data object and outputted to the terminal.

#!/usr/bin/python3

import requests
from requests.exceptions import HTTPError


def get_weather(lat, lng):
    # Build the `payload` for the requested data.
    payload = {
        'lat': lat,
        'lon': lng,
        'unit': 0,
        'lg': 'english',
        'FcstType': 'json'
    }

    # Set the `url` variable with the weather link.
    url = 'https://forecast.weather.gov/MapClick.php'

    try:
        # Send a GET request to retrieve the JSON data.
        response = requests.get(url, params=payload)

        # Check for HTTP errors before processing.
        response.raise_for_status()

        # Return the JSON object of the response.
        json = response.json()

        # Print out the values from the JSON data object.
        print("Location:",    json['location']['areaDescription'])
        print("Temperature:", json['currentobservation']['Temp'] + "°")
        print("Wind:",        json['currentobservation']['Winds'], "mph")
        print("Humidity:",    json['currentobservation']['Relh'] + "%")
        print("Dew Point:",   json['currentobservation']['Dewp'] + "°")
        print("Barometer:",   json['currentobservation']['SLP'], "in")
        print("Visibility:",  json['currentobservation']['Visibility'], "mi")
        print("Forecast:",    json['data']['text'][0])
    except HTTPError as http_err:
        print("HTTP Error Occurred:", http_err)
    except Exception as err:
        print("An Exception Occured:", err)


if __name__ == "__main__":
    # Call the 'get_weather' function and pass the latitude and logitude for
    # the location that we want to retrieve the weather information from.
    get_weather("38.349819", "-81.632622")

Terminal Output:

Location: Charleston WV<br>
Temperature: 69°<br>
Wind: 3 mph<br>
Humidity: 96%<br>
Dew Point: 68°<br>
Barometer: 30.13 in<br>
Visibility: 10.00 mi<br>
Forecast: Areas of fog after 4am.  Otherwise, mostly clear, with a low around 66. Calm wind.

Helpful Tip

There is a lot more weather information available within the JSON data object than is used for this basic project. You can output the entire JSON data object to your terminal or visit the NWS JSON file to see what data is available to use.

#!/usr/bin/python3

import requests
from requests.exceptions import HTTPError


def get_weather(lat, lng):
    # Build the `payload` for the requested data.
    payload = {
        'lat': lat,
        'lon': lng,
        'unit': 0,
        'lg': 'english',
        'FcstType': 'json'
    }

    # Set the `url` variable with the weather link.
    url = 'https://forecast.weather.gov/MapClick.php'

    try:
        # Send a GET request to retrieve the JSON data.
        response = requests.get(url, params=payload)

        # Check for HTTP errors before processing.
        response.raise_for_status()

        # Return the JSON object of the response.
        json = response.json()

        # Print all JSON data to terminal.
        print(json)
        
    except HTTPError as http_err:
        print("HTTP Error Occurred:", http_err)
    except Exception as err:
        print("An Exception Occured:", err)


if __name__ == "__main__":
    # Call the 'get_weather' function and pass the latitude and logitude for
    # the location that we want to retrieve the weather information from.
    get_weather("38.349819", "-81.632622")
Tags: JSONPythonRequestsWeather
ShareTweetSharePinShareShareScan
ADVERTISEMENT
Jonathan Moore

Jonathan Moore

Senior Software Engineer and Cybersecurity Specialist with over 3 decades of experience in developing web, desktop, and server applications for Linux and Windows-based operating systems. Worked on numerous projects, including automation, artificial intelligence, data analysis, application programming interfaces, intrusion detection systems, streaming audio servers, WordPress plugins, and much more.

Related Articles

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Scraping Web Data with Python Helium

Scraping Web Data with Python Helium

If you've ever needed to extract information from a website programmatically, you've likely heard of various tools and libraries. One...

Next Post
Send Email with Python

Send Email with Python

Recommended Services

Latest Articles

Monitoring Web Page Changes with Python

Monitoring Web Page Changes with Python

There are times when I need to know that a web page has changed without actively watching it. That might...

Read moreDetails

My SSH Setup: How I Manage Multiple Servers

My SSH Setup: How I Manage Multiple Servers

If you work with more than one server, the need to manage multiple servers with SSH becomes obvious pretty quickly....

Read moreDetails

Building a Network Tracker Auditor for Privacy with Python

Building a Network Tracker Auditor for Privacy with Python

In my last post, I dug into AdGuard, a robust ad blocker that tackles trackers and ads head-on. But how...

Read moreDetails

AdGuard Ad Blocker Review

AdGuard Ad Blocker Review

Ad blocking software has become essential for anyone who values a clean, fast, and secure browsing experience. With the ever-increasing...

Read moreDetails
  • Privacy Policy
  • Terms of Service

© 2025 JMooreWV. All rights reserved.

No Result
View All Result
  • Home
  • Guides
    • Linux
    • Programming
      • JavaScript
      • PHP
      • Python
    • Tools
    • WordPress
  • Blog
    • Artificial Intelligence
    • Tutorials
    • Privacy
    • Security
  • Apps
    • Bible App
    • Bible Verse Screensaver
    • Blue AI Chatbot
    • Early Spring Predictor
    • FIGlet Generator
    • Password Generator
    • StegX
    • The Matrix
    • WeatherX
    • Website Risk Level Tool
  • About
    • About JMooreWV
    • Live Cyber Attacks
  • Contact
    • General Contact
    • Website Technical Support