Python爬取天气信息,并进行语音播报

发布于:2024-04-10 ⋅ 阅读:(137) ⋅ 点赞:(0)

1、涉及的主要库

  1. requests:requests 是一个Python的HTTP库,用于发送HTTP请求和处理响应。它是基于Python的 urllib 和 httplib 库的封装,提供了更加简洁、易用的接口,使得发送HTTP请求变得更加方便。你可以使用 requests 库来获取网页内容、下载文件、发送POST请求等。它是许多网络爬虫和Web应用程序中常用的库之一。
  2. BeautifulSoup:BeautifulSoup 是一个Python的库,用于解析HTML和XML文档。它能够帮助你从网页中提取数据,例如获取特定标签下的文本内容、链接、图片等。BeautifulSoup 提供了简单而强大的API,使得在Python中处理网页内容变得非常容易。你可以使用它来编写网络爬虫、数据抓取工具或者网页信息提取程序。
  3. pyttsx3:pyttsx3 是一个Python文本到语音(TTS)库,它允许你在Python程序中将文本转换为语音。这个库使用的是本地的文本到语音引擎,可以在不同的操作系统上运行,包括Windows、Linux和Mac OS。使用pyttsx3,你可以将文本转换为语音并进行播放,这在实现语音播报功能时非常有用。

2、实现代码

import requests
from bs4 import BeautifulSoup
import pyttsx3

url = 'http://www.weather.com.cn/weather/101181401.shtml'

response = requests.get(url)
response.encoding = response.apparent_encoding

soup = BeautifulSoup(response.text, features='html.parser')

target = soup.find('ul', class_='t clearfix')

li_list = target.findAll('li')

voice = pyttsx3.init()

for li in li_list:
    date = li.find('h1').text
    wea = li.find('p', class_='wea').text
    temp = li.find('p', class_='tem').text.split('/')
    win = li.find('p', class_='win').text
    win1 = str(win).replace('<', '')
    if len(temp) > 1:
        print(date, temp[0], temp[1], win1)
        voice.say(date)
        voice.say('最高温度' + temp[0])
        voice.say('最低温度' + temp[1])
        voice.say('风力' + win1)
        voice.runAndWait()
    else:
        print(date, temp, win1)
        voice.say(date)
        voice.say('温度' + temp[0])
        voice.say('风力' + win1)
        voice.runAndWait()


网站公告

今日签到

点亮在社区的每一天
去签到