爬虫提取的数据以excel的形式发送到钉钉


第一步:获取access_token 文档:钉钉开发文档

第二步:上传文件,获取media_id 文档:钉钉开发文档

第三步:使用钉钉机器人发送下载链接 文档:钉钉开发文档

第四步:代码编写

import requests import json from urllib3 import encode_multipart_formdata import time def getToken(): ''' 获取最新的access_token''' corpid = 'xxxxxx' secrect = 'xxxxxxxxxx' url = 'https://oapi.dingtalk.com/gettoken?corpid=%s&corpsecret=%s' % (corpid, secrect) req = requests.get(url) access_token = json.loads(req.text) return access_token['access_token'] def get_media_id(file_path,file_name,access_token): '''上传文件并且返回对应的media_id''' url_post=r"https://oapi.dingtalk.com/media/upload?access_token=%s&type=file"%access_token headers={} data={} data['media']= (file_name, open(file_path, 'rb').read()) #说明:file_name,不支持中文,必须为应为字符 encode_data = encode_multipart_formdata(data) data = encode_data[0] headers['Content-Type'] = encode_data[1] r = requests.post(url_post, headers=headers, data=data) media_id=json.loads(r.text)["media_id"] return media_id def send_file(access_token,media_id,url_robot,msg,key): '''通过群机器人发送链接,达到点击链接下载文件的目的''' header = { "Content-Type": "application/json", "Charset": "UTF-8" } send_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) down_load_url="https://oapi.dingtalk.com/media/downloadFile?access_token=%s&media_id=%s"%(access_token,media_id) data={ "actionCard": { "title": "%s"%key, "text": " %s \n\n更新时间:%s "%(msg,send_time), "hideAvatar": "0", "btnOrientation": "0", "btns": [ { "title": "点击下载数据", "actionURL": down_load_url }, ] }, "msgtype": "actionCard" } r = requests.post(url_robot,data=json.dumps(data),headers=header) print (r.text) return json.loads(r.text) def send_file_robot(file_path,url_robot,msg,key): '''依次为文件路径,Webhook地址,需要发送的消息,钉钉安全设置的自定义关键字''' access_token=getToken() file_name=file_path.split('\\')[-1] media_id=get_media_id(file_path,file_name,access_token) result=send_file(access_token,media_id,url_robot,msg,key) print(result) if __name__ == "__main__": url_robot='Webhook地址' file_path=r'C:\Users\Administrator\Desktop\file\test.xlsx'#文件路径 msg='需要说明的话' key='joyooooo' #钉钉安全设置的自定义关键字 send_file_robot(file_path,url_robot,msg,key) 

测试效果:

点击下载数据,弹出下载框:

最终,配合数据提取、拆分模块和定时任务,便可实现数据文件的定时批量发送了~


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM