[Python] 纯文本查看 复制代码import requests
from bs4 import BeautifulSoup as bs
headers = { # 请求头
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
}
new = {} # 天气字典
hostlist = {} # 热搜字典
url_getMsg = 'http://www.weather.com.cn/weather/101300101.shtml' # 获取天气网站,此处为南宁市,可根据个人所在城市更改链接
url_hostlist = 'http://top.baidu.com/' # 百度热搜榜
url_send_QQmsg = '' # 个人QQ推送接口,自行添加
url_send_QQGroupmsg = '' # QQ群推送接口,自行添加
'''获取天气数据部分'''
html = requests.get(url=url_getMsg, headers=headers) # 获取天气网页
html = html.text.encode("raw_unicode_escape").decode("utf-8")
soup = bs(html, 'lxml')
tr_list = soup.find('ul', class_='t clearfix')
tr_list = tr_list.find_all('li')
# 使用find_all查找数据所得为列表,使用find查找数据所得为字符串
tr = tr_list[0] # 清洗数据 可搭建for增加获取天数
tian = tr.find_all('h1')[0].get_text()
wea = tr.find_all('p', class_='wea')[0].get_text()
daymax = tr.find('span').get_text()
daymin = tr.find('i').get_text()
wind = tr.find_all('span')
speed = tr.find_all('i')[1].get_text()
# 一种创建词典方式
new = {'日期': tian, '天气': wea, '最高温度': daymax, '最低温度': daymin, '风向': wind[-1]['title'], '风速': speed}
'''获取热搜数据部分'''
html_hot = requests.get(url=url_hostlist, headers=headers) # 获取百度排行榜热搜
html_hot = html_hot.text.encode("raw_unicode_escape").decode("gbk")
soup_hot = bs(html_hot, 'lxml')
tr_hot = soup_hot.find_all('ul', id='hot-list')
tr_hot = tr_hot[0]
list_hot = tr_hot.find_all('li')
for i in range(0, 3): # 循环int类型字符需要使用range函数
list_title = list_hot[i].find_all('a', class_='list-title')
list_title = list_title[0]['title']
hostlist[i] = list_title # 另一种创建词典方式
'''发送部分'''
page_QQmsg = {
'msg': f'「今日份天气」\n城市:南宁\n{new["日期"]}\n{new["最低温度"]}—{new["最高温度"]}\n风向:{new["风向"]} 风速:{new["风速"]}\n'
f'-----------\n「今日份要闻」:\n1.{hostlist[0]}\n2.{hostlist[1]}\n3.{hostlist[2]}',
}
re = requests.post(url_send_QQmsg, headers=headers, data=page_QQmsg)
group = requests.post(url_send_QQGroupmsg, headers=headers, data=page_QQmsg)