1、涉及的主要库
- requests:
requests
是一个Python的HTTP库,用于发送HTTP请求和处理响应。它是基于Python的 urllib 和 httplib 库的封装,提供了更加简洁、易用的接口,使得发送HTTP请求变得更加方便。你可以使用 requests 库来获取网页内容、下载文件、发送POST请求等。它是许多网络爬虫和Web应用程序中常用的库之一。 - BeautifulSoup:
BeautifulSoup
是一个Python的库,用于解析HTML和XML文档。它能够帮助你从网页中提取数据,例如获取特定标签下的文本内容、链接、图片等。BeautifulSoup 提供了简单而强大的API,使得在Python中处理网页内容变得非常容易。你可以使用它来编写网络爬虫、数据抓取工具或者网页信息提取程序。 - 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()