很久之前写了一个爬虫脚本,每10分钟获取一次比特币价格,当价格波动较大时,使用邮件通知我进行交易。之前的脚本部署在学校的群晖上,由于会时不时地停电,爬虫脚本运行状态很不稳定,这段时间接触了github action ,感觉正好满足我的需求,于是将爬虫迁移到到GitHub Action上,并弃用原来Python实现的邮件发送功能,改为利用Github Action实现邮件通知。
项目地址:https://github.com/lsqls/bitcoin
编写爬虫脚本
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
| import requests import os from lxml import etree from jinja2 import Environment, PackageLoader max=10000;min=4000
if 'MAX' in os.environ: max=float(os.getenv('MAX')) if 'MIN' in os.environ: min=float(os.getenv('MIN')) sendemail=False;strategy="继续持有"
url='https://price.btcfans.com/' html = etree.HTML(requests.get(url).text) price = float(html.xpath('//li[@id="coin-bitcoin"]//span[@class="last-price"]/text()')[0].replace(',',''))
if (price>max): sendemail=True strategy="卖出" if (price<min): sendemail=True strategy="买入"
env = Environment(loader=PackageLoader('bitcoin', '')) template = env.get_template('template.html') template.stream(price=price,max=max,min=min,strategy=strategy).dump('email.html')
print("::set-env name=sendemail::{}".format(sendemail))
|
脚本非常简单,可以分为以下几步:
编写workflow文件
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 34 35 36 37 38 39 40
| name: 'bitcoin'
on: push: branches: - master schedule: - cron: '*/10 * * * *' jobs: GetBtcPrice: runs-on: ubuntu-latest steps: - name: 'Checkout codes' uses: actions/checkout@v2 - name: 'Setup python' uses: actions/setup-python@v1 with: python-version: '3.x' - name: 'Install dependencies' run: python -m pip install --upgrade requests lxml jinja2 - name: 'run get price script' env: MAX: ${{ secrets.MAX }} MIN: ${{ secrets.MIN }} run: python bitcoin.py - name: Send mail if: ${{ env.sendemail == 'True' }} uses: dawidd6/action-send-mail@v2 with: server_address: smtp.163.com server_port: 465 username: ${{secrets.MAIL_USERNAME}} password: ${{secrets.MAIL_PASSWORD}} subject: 比特币价格监控 body: file://email.html to: ${{secrets.TO}} from: ${{secrets.MAIL_USERNAME}} content_type: text/html
|
脚本每10分钟执行一次,cron的设置语法和Linux下的crontab一致
在secrets中设置MAX
、MIN
、MAIL_USERNAME
、MAIL_PASSWORD
、TO
(接收邮箱地址)以保证脚本的正常运行
Fork 的仓库上 GitHub Actions 的定时任务不会自动执行,必须要手动触发一次后才能正常工作,随便改点什么提交就行

参考文章与项目
http://www.ruanyifeng.com/blog/2019/09/getting-started-with-github-actions.html
http://www.ruanyifeng.com/blog/2019/12/github_actions.html
https://github.com/Closty/chaoxing/
https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idif