获取比特币价格脚本

最近入门币圈, 希望能够方便的获取”比特币”的价格, 而不需要打开网页才能获取到. 在网上搜索了一圈, 没有找到合适的脚本. 一拍脑袋, 决定自己写一个python脚本. 本人对python不熟, 希望懂python的大神, 手下留情. 如果觉得有帮助, 可以扫描右边的微信打赏码支持一下. 话不多说, 直接贴上获取 bitcoinprice.com 网站比特币价格的脚本程序:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import sys
from urllib.parse import quote
import string
import json

def output(msg):
    print(msg)

def parse():
    headers = {"Accept": "text/html,application/xhtml+xml,application/xml;",
               "Accept-Encoding": "gzip",
               "Accept-Language": "zh-CN,zh;q=0.8",
               "Referer": "http://www.example.com/",
               "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \
                             Chrome/42.0.2311.90 Safari/537.36"
               }
    url = 'https://www.bitcoinprice.com/'
    s = requests.Session()
    s.headers.update(headers)
    try:
        r = s.get(url)
    except Exception:
        output('BTC $0')
        exit()

    return BeautifulSoup(r.text, 'html.parser')

if __name__ == '__main__':
    prefix = '<script type="application/ld+json">'
    postfix = '</script>'

    soup = parse()
    array = soup.find_all('script', type='application/ld+json')
    for i in array:
        i = i.prettify()
        s = i.find(prefix)
        e = i.find(postfix)

        if s == -1 or e == -1:
            continue

        s += len(prefix)
        json_str = i[s:e]
        data = json.loads(json_str)

        for j in data['@graph']:
            if j['name'] == 'BTC':
                price = round(float(j['offers']['price']))
                info =  j['name'] + ' $' + str(price)
                output(info)
                exit()

    output('BTC $0')