实时语音天气播报系统

1. 获取天气信息

网址:http://www.weather.com.cn/textFC/beijing.shtml
没有反爬
源码

# @Time : 2020/1/18 20:54
# @Author : GKL
# FileName : spider.py
# Software : PyCharm

import requests
from lxml import etree
from public.operation_db import *


class Spider(object):

    def __init__(self):
        self.url = 'http://www.weather.com.cn/textFC/beijing.shtml'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
            'Cookie': 'HttpOnly; HttpOnly; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1579350900; vjuids=-2a76eb78b.16fb8a63ed3.0.ee0d8ff2241ba; vjlast=1579350900.1579350900.30; userNewsPort0=1; f_city=%E9%93%9C%E4%BB%81%7C101260601%7C; Wa_lvt_1=1579350903; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1579352000; Wa_lpvt_1=1579352000'
        }
        self.base_url = 'http://www.weather.com.cn'

    def get_province(self):
        """
        获取省份信息
        :return:
        """
        response = requests.get(self.url, headers=self.headers).content.decode('utf-8')
        # print(response)
        page = etree.HTML(response)

        provinces = page.xpath('//div[@class="lqcontentBoxheader"]/ul/li/a/text()')
        url_list = page.xpath('//div[@class="lqcontentBoxheader"]/ul/li/a/@href')
        return provinces, url_list

    def get_weather(self, provinces, url_list):
        """
        获取天气信息
        :param provinces:
        :param url_list:
        :return:
        """
        for province, url in zip(provinces, url_list):
            link = self.base_url + url
            response = requests.get(link, headers=self.headers).content.decode('utf-8')

            page = etree.HTML(response)

            node_list = page.xpath('//div[@class="conMidtab"][2]//div[@class="conMidtab3"]//tr[position()>1]')
            try:
                # 重点城市信息
                first_node = page.xpath('//div[@class="conMidtab"][2]//div[@class="conMidtab3"]//tr[1]')

                for node in first_node:
                    city = node.xpath('./td[2]/a/text()')[0]
                    weather = node.xpath('./td[3]/text()')[0]
                    wind = node.xpath('./td[4]/span/text()')[0]
                    max_temp = node.xpath('./td[5]/text()')[0]
                    min_temp = node.xpath('./td[8]/text()')[0]
                    print(city)
                    sql = 'insert into weather(city, weather, wind, max_temp, min_temp) values(%s, %s,%s,%s,%s)'
                    insert_one(sql, (city, weather, wind, max_temp, min_temp))
            except Exception:
                pass


            # 普通城市信息
            for node in node_list:
                city = node.xpath('./td[1]/a/text()')[0]
                weather = node.xpath('./td[2]/text()')[0]
                wind = node.xpath('./td[3]/span/text()')[0]
                max_temp = node.xpath('./td[4]/text()')[0]
                min_temp = node.xpath('./td[7]/text()')[0]
                print(city)

                sql = 'insert into weather(city, weather, wind, max_temp, min_temp) values(%s, %s,%s,%s,%s)'
                insert_one(sql, (city, weather, wind, max_temp, min_temp))


if __name__ == '__main__':
    s = Spider()
    provinces, url_list = s.get_province()
    s.get_weather(provinces, url_list)
2. 语音合成及播放

百度api:https://blog.csdn.net/gklcsdn/article/details/103204955

# @Time : 2020/1/18 21:42
# @Author : GKL
# FileName : audio.py
# Software : PyCharm


import time
import pygame
from aip import AipSpeech
from public.operation_db import *


def conAudio():
    """
    拼接语音数据
    :return:
    """
    city = input('请输入城市名>>>: ')
    # city = '海南'
    sql = 'select * from weather where city="%s"' % city
    tuple_data = select_data(sql)

    # 天气情况
    weather = tuple_data[0][2]

    # 风向
    wind = tuple_data[0][3]

    # 最高温
    max_hot = tuple_data[0][4]

    # 最低温
    min_hot = tuple_data[0][5]

    # 语音数据
    data = city + '市天气' + weather + '风向' + wind + '最高温' +  max_hot  + '度' + '最低温' + min_hot + '度'

    if '-' in data:
        data = data.replace('-', '负')

    print(data)
    return data, city


def audio(data, city):
    """
    合成语音
    :param data:
    :param city:
    :return:
    """

    """ 你的 APPID AK SK """
    APP_ID = ''
    API_KEY = ''
    SECRET_KEY = ''

    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

    result = client.synthesis(data, 'zh', 1, {
        'vol': 15,  # 音量
        'spd': 3,  # 语速
        'pit': 9,  # 语调
        'per': 4,  # 0:女 1:男 3:逍遥 4:小萝莉
    })
    # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
    if not isinstance(result, dict):
        filename = city + '.mp3'
        # if filename:
        #     os.remove(filename)
        try:
            with open(filename, 'wb') as f:
                f.write(result)
        except Exception:
            pass



def raed(city):
    """
    python 读取MP3文件逻辑
    :param city:
    :return:
    """
    filepath = "{}.mp3".format(city)

    pygame.mixer.init()

    # 加载音乐
    pygame.mixer.music.load(filepath)

    # 播放音乐
    pygame.mixer.music.play()

    # 播放音乐的时间,没有睡眠时间 ,程序一下就会执行完 ,音乐播放不出来
    time.sleep(7)

    # 关闭音乐
    pygame.mixer.music.stop()


def run():
    """
    运行调用逻辑
    :return:
    """
    while True:
        try:
            data, city = conAudio()
        except Exception:
            print('输入城市有误,请重新输入')
        else:

            audio(data, city)
            raed(city)



if __name__ == '__main__':
    # p1 = Process(target=run)
    # p1.start()

    run()

3. 打包

pyinstaller -F -i audio.ico audio.py

4. 使用

打开exe文件,输入城市名,会自动播报天气信息
在这里插入图片描述

5. 后续将爬虫代码放到服务器上稳定运行实现实时更新
发布了288 篇原创文章 · 获赞 50 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/gklcsdn/article/details/104034991
今日推荐