实现效果图
代码分析
import requests #这个库用来获取网页信息
from bs4 import BeautifulSoup #这个库用来分析选择网页的信息
def get_content(url, data=None): #获取城市的天气网页信息
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return '产生异常'
def get_data(html,city): #处理网页信息提取近七天的天气情况
final_list = []
soup = BeautifulSoup(html, 'html.parser')
body = soup.body
data = body.find('div', {'id': '7d'})
ul = data.find('ul')
lis = ul.find_all('li')
for day in lis:
temp_list = [city]
date = day.find('h1').string
temp_list.append(date)
info = day.find_all('p')
temp_list.append(info[0].string)
if info[1].find('span') is None:
temperature_highest = ' '
else:
temperature_highest = info[1].find('span').string
temperature_highest = temperature_highest.replace('℃', ' ')
if info[1].find('i') is None: #
temperature_lowest = ' '
else:
temperature_lowest = info[1].find('i').string
temperature_lowest = temperature_lowest.replace('℃', ' ')
temp_list.append(temperature_highest)
temp_list.append(temperature_lowest)
wind_scale = info[2].find('i').string
temp_list.append(wind_scale)
final_list.append(temp_list)
return final_list
def save_data(data,filename): #将近七天的天气信息存放在文件中
f=open(filename,"wt")
for line in data:
f.write(str(line)+'\n')
f.close()
def postrsg(filename): #取出信息并且用机器人发送消息
with open(filename,'r') as f:
lines = f.readlines()
first = lines[0]
sec = lines[1].rstrip("\n")
headers = {"Content-Type": "text/plain"}
data = {
"msgtype": "text",
"text": {
"content": first+sec,
}
}
r = requests.post(
url='群机器人webhook地址',headers=headers, json=data)
print(r.text)
if __name__ == '__main__':
url ='http://www.weather.com.cn/weather/101020100.shtml'
html = get_content(url)
result = get_data(html,'上海')
save_data(result,'w.txt')
postrsg('w.txt')
定时发送
利用crontab,编写crontab.cron文件
//eg.
//每天早上6点
//注意单纯echo,从屏幕上看不到任何输出,因为cron把任何输出都email到root的信箱了。
0 6 * * * echo "Good morning." >> /tmp/test.txt
//每两个小时(第一个为15,指明没两个小时的第15min中执行一次)
15 */2 * * * echo "Have a break now." >> /tmp/test.txt
//晚上11点到早上8点之间每两个小时和早上八点
0 23-7/2,8 * * * echo "Have a good dream" >> /tmp/test.txt
修改完crontest.cron后执行:
crontab crontest.cron >~/log
sudo /etc/init.d/cron restart
参考:
step1 : 用python编写抓取天气的脚本
- https://blog.csdn.net/qq_40958485/article/details/85067636
step2 : python下使用curl使机器人发送消息
- https://blog.csdn.net/qq_43422918/article/details/92798409
step3 : 利用cron定时运行脚本
- https://www.cnblogs.com/kaituorensheng/p/4494321.html