爬虫提取的数据以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"
