current position:Home>Case: Python weather broadcast system, this is a rainy day

Case: Python weather broadcast system, this is a rainy day

2022-05-15 03:08:43Five packs of spicy strips!


​ Hello everyone , I'm spicy

I believe everyone can feel the changeable weather recently , Several times, the weather changed on the way out . Spicy strips are also deeply disturbed , Just fix my cold , Almost isolated , Since I can't decide the weather , That's better than using it python The whole weather crawler to get the weather . In this way, we can carry out an early prevention

 Insert picture description here




pyttsx3: Voice broadcast Library

Weather data sources

​ Find a weather website

 Insert picture description here

For example, we need to check the weather of a place , After entering the place name, you can see the result .

 Insert picture description here

We can see the url There will be changes : Insert picture description here

Weather information for each city url Is to add city Pinyin at the back of the website , In this case, we can use function parameters to solve the problem of city input .

Code implementation

#  How to get the weather 
def get_weather(city):
    #  Weather website   character string 
    url = '' + city + '/'

    #  A vest disguised as a browser 
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.58'

    #  Initiate a web request and get the web page code 
    website = requests.get(url=url, headers=headers)

    data = etree.HTML(website.text)     #  Data preprocessing 
	#xpath Analyze the weather data on the page 
    weather_list = data.xpath('//dl[@class="weather_info"]//text()')

    weather_text = ' Welcome to the weather broadcast assistant , Here's what you want to know about the city weather :\n'

    for text in weather_list:
        weather_text += text
        if weather_text.find('[ Switch cities ]'):
            weather_text = weather_text.strip('[ Switch cities ]')

    return weather_text

In this way, the crawler can get the weather data of each city , Re pass pyttsx3 Build a voice object instance , Just put the weather text in and run it .

if __name__ == '__main__':
    city = input(' Please enter your city , For example, Changsha :changsha-->').strip()
    weather_info = get_weather(city)        # weather_info To get the captured weather text 
    weather = pyttsx3.init()            #  Initialize the speaking object 
    weather.say(weather_info)           #  Set what to say 
    weather.runAndWait()                #  Start speaking 


This is the preparation of the physical class , Through the principle of defeating magic with magic ~ Ha ha ha

copyright notice
author[Five packs of spicy strips!],Please bring the original link to reprint, thank you.

Random recommended