Python Script for Weather, Password Hashing, HTML Parsing, and Time Display

  • Share this:

Code introduction


This function uses multiple Python libraries to fetch and parse weather information, hash passwords, parse HTML documents, and get the current time. It first fetches weather information for a specified city, then hashes the password, parses the HTML document of a given URL to get the title, and finally outputs the current time.


Technology Stack : Python, requests, datetime, hashlib, BeautifulSoup

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import datetime
from hashlib import sha256
from bs4 import BeautifulSoup
import requests

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def get_weather(city_name):
    API_KEY = 'your_api_key_here'
    BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        'q': city_name,
        'appid': API_KEY,
        'units': 'metric'
    }
    response = requests.get(BASE_URL, params=params)
    return response.json()

def hash_password(password):
    return sha256(password.encode()).hexdigest()

def parse_html(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    return soup.find('h1').text

def get_current_time():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def xxx(city_name, password, url):
    city_weather = get_weather(city_name)
    hashed_password = hash_password(password)
    website_title = parse_html(url)
    current_time = get_current_time()
    
    print(f"Weather in {city_name}: {city_weather['weather'][0]['description']}")
    print(f"Hashed Password: {hashed_password[:10]}")
    print(f"Website Title: {website_title}")
    print(f"Current Time: {current_time}")

# Example usage:
# xxx("London", "mypassword123", "https://example.com")