利用Automator和Python下载数据

需求:

1.从某个网站下载更新的数据,周二至周六更新前一天数据

2.将数据归类到相应路径文件夹

3.将文件按照日期重命名

参考文档:Python 搭配 Automator 上传文件到 Github

Python脚本(脱敏)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding:utf8 -*-
#上一行是为了解决python中识别中文注释问题

import requests
import datetime

DATA_URL_ARKK_PDF = ''
DATA_URL_ARKK_CSV = ''

DATA_MAINPATH = '/Users/shawleo/Desktop/ARK/Data'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'

# 北京时间每周二至周六晚上9点执行

theHeader = {'User-Agent': USER_AGENT}
today = datetime.date.today()
formatted_today=today.strftime('%y%m%d')
yesterday=int(formatted_today)-1

path_ARKK_PDF = DATA_MAINPATH + '/ARKK/' + 'ARKK' + '20' + str(yesterday) + '.pdf'
path_ARKK_CSV = DATA_MAINPATH + '/ARKK/' + 'ARKK' + '20' + str(yesterday) + '.csv'

response = requests.get(DATA_URL_ARKK_PDF, headers=theHeader, stream=True)

with open(path_ARKK_PDF, "wb") as f:
for chunk in response.iter_content(chunk_size=512):
f.write(chunk)

response = requests.get(DATA_URL_ARKK_CSV, headers=theHeader, stream=True)

with open(path_ARKK_CSV, "wb") as f:
for chunk in response.iter_content(chunk_size=512):
f.write(chunk)

搭配 Automator 使用

上面的脚本已经可以使用了,但是每次跑命令行依然很麻烦,苹果电脑提供了一个叫做 Automator (自动操作) 的软件,可以帮助我们建立工作流程,我们可以借助它来帮我们跑脚本。

1.新建一个日历提醒:

image

2.插入工作日判断

image

搜索applescript,拖进去,输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
on run

#判断日期,周日和周一不运行

set currentDay to weekday of (get current date)



if currentDay ≠ Sunday and currentDay ≠ Monday then


return true


end if


error number -128
#中止执行该workflow,
end run

参考:

1
2
3
4
display dialog "Do you want to exit this workflow?" with icon note buttons {"Exit", "Continue"}
if the button returned of the result is "Exit" then
error number -128
end if

参考来源:

Determine if today is [day of week], then run action?

如何告诉Applescript停止执行?

How to tell an Applescript to stop executing

3.插入提示

这一步的目的是让 AppleScript 弹出一个提示。

添加一个运行 AppleScript 脚本:
image

1
2
3
4
on run {input, parameters}
display notification "⬆️ 开始上传"
return input
end run

4.配置 shell 脚本

增加一个运行 Shell 脚本 (注意使用bash来执行脚本):【zsh与bash兼容】
image

在其中写上:

1
2
3
4
5
/usr/local/bin/python3 <<EOF

把上一步中配置好的 Python 脚本复制到这里

EOF

其中的 /usr/local/bin/python3 <<EOF 和 EOF 写法是一个 Hack,如果直接选择使用 python 执行,会出现找不到 Python 第三方库的情况,所以用了这个 Hack 的办法。

image

5.结果图

image

6.保存

参考:Mac下自动化神器–扛炮

Command+S 保存这个动作, 起一个名字, 之后会弹出日历.

将事件拖放到未来某一天, 双击事件, 在弹出框里点击日期栏会展开, 然后选择 repeat 栏目下的重复周期, 可以设置每周执行一次, 每月执行一次等.

每日执行一次

重复-每天

结束日期时间不要动,都选择9点即可

image

上述操作不知道为什么,对于我的电脑无效,只能采取其他方式了:

按住command 多选复制 再粘贴

image

附:该application所在路径:

image