python微信公众号自动推送(十分简单的教程)

目录

一、注册微信公众号

1.注册链接

2.登录成功

3.关注该公众号

4.创建模板

二、代码实现

1.爬取天气信息

2.计算生日天数

3.获取access token

4.获取关注者的openid

5.向用户广播消息

6.最终代码

一、注册微信公众号1.注册链接

https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index ;

到达这个界面微信扫码登录即可(若出现登录失败问题则建议换一个更好的网络环境再尝试或者尝试刷新网页)

2.登录成功

登录成功后会自动生成你的appid和appsecret(后面会用到) 接口信息等暂时不用管若后期想完全实现自动推送则需要挂自己的服务器(后续会更新)

3.关注该公众号

扫码关注即可(建议不要心急自己调试好了再让npy关注)

4.创建模板

创建模板时既可以将所有的 文本文字+数据 放在一起当作数据像这样

也可以再模板内先写出来,但是这种方法会让模板的灵活性变小做大的修改只能重新创建新的模板

创建好模板微信公众号注册的工作就结束了

二、代码实现

首先了解以下的几个库

import requestsimport jsonimport datetimeimport timefrom bs4 import BeautifulSoupfrom zhdate import ZhDate#用到的库1.爬取天气信息def get_weather(self):””” 该方法中用到了beautifulsoup的一些基本用法 感兴趣可以深入了解python爬虫””” url = ‘http://www.weather.com.cn/weather/101290101.shtml’ #昆明天气网站 sysdate = datetime.date.today() r = requests.get(url, timeout=30) # 用requests抓取网页 r.raise_for_status() # 异常时停止 r.encoding = r.apparent_encoding # 编码格式 html = r.text final_list = [] soup = BeautifulSoup(html, ‘html.parser’) # 用BeautifulSoup库解析网页 body = soup.body # 从soup里截取body的一部分 data = body.find(‘div’, {‘id’: ‘7d’}) #在网页浏览器按F12遍历div 找到 id = 7d #的对应标签 会发现七天的天气信息都包括在子节点中 ul = data.find(‘ul’) #用find方法找ul标签 lis = ul.find_all(‘li’) #找到ul中的li标签也就是列表其中存放着 日期 天气 风力等信息 for day in lis: temp_list = [] date = day.find(‘h1’).string # 找到日期 if date.string.split(‘日’)[0] == str(sysdate.day): temp_list = [] date = day.find(‘h1’).string # 找到日期 temp_list.append(date) info = day.find_all(‘p’) # 找到所有的p标签 temp_list.append(info[0].string) if info[1].find(‘span’) is None: # 找到p标签中的第二个值’span’标签——最高温度 temperature_highest = ‘ ‘ # 用一个判断是否有最高温度 else: temperature_highest = info[1].find(‘span’).string temperature_highest = temperature_highest.replace(‘℃’, ‘ ‘) if info[1].find(‘i’) is None: # 找到p标签中的第二个值’i’标签——最高温度 temperature_lowest = ‘ ‘ # 用一个判断是否有最低温度 else: temperature_lowest = info[1].find(‘i’).string temperature_lowest = temperature_lowest.replace(‘℃’, ‘ ‘) temp_list.append(temperature_highest) # 将最高气温添加到temp_list中 temp_list.append(temperature_lowest) # 将最低气温添加到temp_list中 final_list.append(temp_list) # 将temp_list列表添加到final_list列表中 return ‘天气情况:’ + final_list[0][1] + ‘\n温度:’ + final_list[0][3].strip() + ‘~’ + \ final_list[0][2].strip() + ‘℃’2.计算生日天数 def get_herbirthday(self):””” 获取npy生日 这里还用到了农历时间库 可以去网上查阅 ZhDate库 其他基本上是datetime中的一些获取当前日期和toordinal 没什么特别难的””” today = datetime.datetime.now() #获取现在时间信息 data_str = today.strftime(‘%Y-%m-%d’) herbirthDay = ZhDate(today.year, 1, 18).to_datetime() #将农历1.18号的时间转换为公历时间再转换为datetime类型的时间 if herbirthDay >today : #如果ta的生日日期比今天靠后则直接计算这两天的序号之差 difference = herbirthDay.toordinal() – today.toordinal() return (“\n距离熊又又生日,还有 %d 天。” % (difference)) elif herbirthDay3.获取access token

获取公众号的access_token值,access_token是公众号全局唯一接口调用凭据,公众号调用各接口时都需要使用access_token。 api接口:接口调用请求说明https请求方式:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={你的appid}&secret={你的appsecret} def get_access_token(self):””” 获取access_token 通过查阅微信公众号的开发说明就清晰明了了””” url = ‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}’.\ format(self.appID, self.appsecret) headers = { ‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36’ } response = requests.get(url, headers=headers).json() access_token = response.get(‘access_token’) return access_token4.获取关注者的openid

opend_id是(有关注公众号的微信账号)用户id,想要消息推送过去就必须要获取open_id

获取open id的https请求方式为

https://api.weixin.qq.com/cgi-bin/user/get?access_token={获取的access token}&next_openid={}def get_openid(self):””” 获取所有用户的openid 微信公众号开发文档中可以查阅获取openid的方法””” next_openid = ” url_openid = ‘https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s’ % (self.access_token, next_openid) ans = requests.get(url_openid) open_ids = json.loads(ans.content)[‘data’][‘openid’] return open_ids5.向用户广播消息

http请求方式:

POST https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKENdef sendmsg(self):””” 给所有用户发送消息””” url = “https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}”.format(self.access_token) if self.opend_ids != ”: for open_id in self.opend_ids: body = { “touser”: open_id, “template_id”: self.template_id, “url”: “https://www.baidu.com/”, “topcolor”: “#FF0000”, #对应模板中的数据模板 “data”: { “frist”: { “value”: self.dataJson.get(“frist”), “color”: “#FF99CC” #文字颜色 }, “body”: { “value”: self.dataJson.get(“body”), “color”: “#EA0000” }, “weather”: { “value”: self.dataJson.get(“weather”), “color”: “#00EC00” }, “date”: { “value”: self.dataJson.get(“date”), “color”: “#6F00D2” }, “remark”: { “value”: self.dataJson.get(“remark”), “color”: “#66CCFF” } } } data = bytes(json.dumps(body, ensure_ascii=False).encode(‘utf-8′)) #将数据编码json并转换为bytes型 response = requests.post(url, data=data) result = response.json() #将返回信息json解码 print(result) # 根据response查看是否广播成功 else: print(“当前没有用户关注该公众号!”)6.最终代码import requestsimport jsonimport datetimeimport timefrom bs4 import BeautifulSoupfrom zhdate import ZhDateclass SendMessage(): #定义发送消息的类 def __init__(self): date = self.get_date() #获取当前日期 weather = self.get_weather() #获取天气信息 lovedate = self.get_loveday() #获取纪念日 herbirthday = self.get_herbirthday() #获取npy生日 mybirthday = self.get_mybirthday() #获取自己生日 body =lovedate+”\n”+herbirthday+mybirthday self.dataJson ={“frist”:”早上好bb!❤\n”, #最终要发送的json “date”:date+’\n’, “body”:body+” “, “weather”:weather+’\n城市:昆明’+’\n’, #因为还没写获取地理位置的所以城市暂时写死 后续将会改为获取当前位置并爬取对应城市的天气信息版本 “last”:’\n今天也是爱bb🐖的一天捏!!!’ } self.appID = ” #appid 注册时有 self.appsecret = ” #appsecret 同上 self.template_id = ” # 模板id self.access_token = self.get_access_token() #获取 access token self.opend_ids = self.get_openid() #获取关注用户的openid def get_weather(self):””” 该方法中用到了beautifulsoup的一些基本用法 感兴趣可以深入了解python爬虫””” url = ‘http://www.weather.com.cn/weather/101290101.shtml’ #昆明天气网站 sysdate = datetime.date.today() r = requests.get(url, timeout=30) # 用requests抓取网页信息 r.raise_for_status() # 异常时停止 r.encoding = r.apparent_encoding # 编码格式 html = r.text final_list = [] soup = BeautifulSoup(html, ‘html.parser’) # 用BeautifulSoup库解析网页 #soup里有对当前天气的建议 body = soup.body # 从soup里截取body的一部分 data = body.find(‘div’, {‘id’: ‘7d’}) #在网页浏览器按F12遍历div 找到 id = 7d 的对应标签 会发现七天的天气信息都包括在子节点中 ul = data.find(‘ul’) #用find方法找ul标签 lis = ul.find_all(‘li’) #找到ul中的li标签也就是列表其中存放着 日期 天气 风力等信息 for day in lis: temp_list = [] date = day.find(‘h1’).string # 找到日期 if date.string.split(‘日’)[0] == str(sysdate.day): temp_list = [] date = day.find(‘h1’).string # 找到日期 temp_list.append(date) info = day.find_all(‘p’) # 找到所有的p标签 temp_list.append(info[0].string) if info[1].find(‘span’) is None: # 找到p标签中的第二个值’span’标签——最高温度 temperature_highest = ‘ ‘ # 用一个判断是否有最高温度 else: temperature_highest = info[1].find(‘span’).string temperature_highest = temperature_highest.replace(‘℃’, ‘ ‘) if info[1].find(‘i’) is None: # 找到p标签中的第二个值’i’标签——最高温度 temperature_lowest = ‘ ‘ # 用一个判断是否有最低温度 else: temperature_lowest = info[1].find(‘i’).string temperature_lowest = temperature_lowest.replace(‘℃’, ‘ ‘) temp_list.append(temperature_highest) # 将最高气温添加到temp_list中 temp_list.append(temperature_lowest) # 将最低气温添加到temp_list中 final_list.append(temp_list) # 将temp_list列表添加到final_list列表中 return ‘天气情况:’ + final_list[0][1] + ‘\n温度:’ + final_list[0][3].strip() + ‘~’ + \ final_list[0][2].strip() + ‘℃’ def get_date(self):””” 这些都是datetime库中的用法 若零基础可以去python的开发文档中查阅””” sysdate = datetime.date.today() # 只获取日期 now_time = datetime.datetime.now() # 获取日期加时间 week_day = sysdate.isoweekday() # 获取周几 week = [‘星期一’, ‘星期二’, ‘星期三’, ‘星期四’, ‘星期五’, ‘星期六’, ‘星期天’] return ‘现在是’ + str(now_time)[0:16] + ‘ ‘ + week[week_day – 1] def get_herbirthday(self):””” 获取npy生日 这里还用到了农历时间库 可以去网上查阅 ZhDate库 其他基本上是datetime中的一些获取当前日期和toordinal 没什么特别难的””” today = datetime.datetime.now() #获取现在时间信息 data_str = today.strftime(‘%Y-%m-%d’) herbirthDay = ZhDate(today.year, 1, 18).to_datetime() #将农历1.18号的时间转换为公历时间再转换为datetime类型的时间 if herbirthDay >today : #如果ta的生日日期比今天靠后则直接计算这两天的序号之差 difference = herbirthDay.toordinal() – today.toordinal() return (“\n距离熊又又生日,还有 %d 天。” % (difference)) elif herbirthDay today : difference = mybirthDay.toordinal() – today.toordinal() return (“\n距离刘壮壮生日,还有 %d 天。” % (difference)) elif mybirthDay

代码还有很多需要改进的地方

大佬轻喷!!!

Original: https://blog.csdn.net/weixin_64200441/article/details/126953445Author: Chris wen504Title: python微信公众号自动推送(十分简单的教程)

相关阅读Title: python画散点图文章目录前言一、散点图函数二、函数参数介绍三、代码实例总结前言

最近在搞聚类算法,所以难免会用到一些散点图的用法,总结一下,方便以后参考。

一、散点图函数首先调用一下画图的库

import matplotlib.pyplot as pltplt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, , edgecolors=None, plotnonfinite=False, data=None, *kwargs)

记得用完了这个函数要show一下,不然成不了图片

plt.show()

二、函数参数介绍

x,y:长度相同的数组,也就是我们即将绘制散点图的数据点,输入数据。用来表示散点图的横纵坐标,例如一个(100,99)的数据,x=100,y=99

s:点的大小,默认 20,也可以是个数组,数组每个参数为对应点的大小,数值越大对应的图中的点越大。

c:点的颜色,默认蓝色 ‘b’,也可以是个 RGB 或 RGBA 二维行数组。写一下常用的颜色所对应的数组:‘b’ blue‘g’ green‘r’ red‘c’ cyan‘m’ magenta‘y’ yellow‘k’ black‘w’ white

marker:点的样式,默认小圆圈 ‘o’。常用的点的样式:‘.’:点(point marker)‘,’:像素点(pixel marker)‘o’:圆形(circle marker)‘v’:朝下三角形(triangle_down marker)‘^’:朝上三角形(triangle_up marker)‘

cmap:Colormap,默认 None,标量或者是一个 colormap 的名字,只有 c 是一个浮点数数组的时才使用。如果没有申明就是 image.cmap。还没搞明白这玩意的用法。

norm:Normalize,默认 None,数据亮度在 0-1 之间,只有 c 是一个浮点数的数组的时才使用,改变点的亮度。

vmin,vmax:亮度设置,在 norm 参数存在时会忽略。

alpha:透明度设置,0-1 之间,默认 None,即不透明。

linewidths:标记点的长度。

edgecolors:颜色或颜色序列,默认为 ‘face’,可选值有 ‘face’, ‘none’, None。表示的是点的描边的颜色,例如 edgecolors=’r’ 就是让边的颜色为红色。

plotnonfinite::布尔值,设置是否使用非限定的 c ( inf, -inf 或 nan) 绘制点。

**kwargs::其他参数。

三、代码实例

在这里我们先引入一个点的数据命名为 data.txt

151,54137,5595,66156,91193,10158,104133,105120,118167,136110,14996,17422,18460,19388,198177,202213,235133,249127,25570,25740,27364,271168,286126,325132,335

读入点的数据并画图,我们这里是用的pandas读的,pandas读出来之后数据格式比较麻烦,我们得对他进行数据处理。

import matplotlib.pyplot as pltimport pandas as pd#读入文件file_path = “data.txt”df = pd.read_table(file_path, header=None)#定义 x y变量x = []y = []#定义颜色变量color = [‘c’, ‘b’, ‘g’, ‘r’, ‘m’, ‘y’, ‘k’, ‘w’]#用for循环将文件中的值赋值给x,yfor i in range(len(df[0])): x.append(int(df[0][i].split(‘,’)[0])) y.append(int(df[0][i].split(‘,’)[1]))#画图plt.scatter(x, y, c=color[1], edgecolors=’r’)plt.show()

代码所示图的样式:

在这里我在附一张用Kmeans聚类算法画的图。这里我聚成了4个类,分别用不同的颜色和图形来表示,效果很明显。总结

散点图的函数参数有很多,但常用的参数为(x,y,c,marker,edgecolors),其余的如果不是特别专业基本用不到。还有就是里面所用到的参数都是list类型,如果不是记得将他们转换。

本文参数的类型介绍参考至菜鸟教程:Matplotlib 散点图,附上网址https://www.runoob.com/matplotlib/matplotlib-scatter.html,如有侵权联系删除。

Original: https://blog.csdn.net/qq_42804105/article/details/124296152Author: 爱写代码的十一Title: python画散点图

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/283309/

转载文章受原作者版权保护。转载请注明原作者出处!


比丘资源网 » python微信公众号自动推送(十分简单的教程)

发表回复

提供最优质的资源集合

立即查看 了解详情