Pytthon 爬取臺灣銀行牌告匯率
源自於https://steam.oxxostudio.tw/category/python/spider/exchange.html
import requests
import paho.mqtt.client as mqtt #import the client1
import time
publish=[]
#=================================#
def on_message(client, userdata, message):
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
#=================================#
broker_address="broker.mqtt-dashboard.com"
#broker_address="iot.eclipse.org"
print("creating new instance")
client = mqtt.Client("P1") #create new instance
client.on_message=on_message #attach function to callback
print("connecting to broker --> ",broker_address )
client.connect(broker_address) #connect to broke
#=================================#
url = 'https://rate.bot.com.tw/xrt/flcsv/0/day' # 牌告匯率 CSV 網址
# https://rate.bot.com.tw/xrt/flcsv/0/day
rate = requests.get(url) # 爬取網址內容
rate.encoding = 'utf-8' # 調整回應訊息編碼為 utf-8,避免編碼不同造成亂碼
rt = rate.text # 以文字模式讀取內容
rts = rt.split('\n') # 使用「換行」將內容拆分成串列
#============MQTT===================#
client.loop_start() #start the loop
#============Line Notify===================#
url = 'https://notify-api.line.me/api/notify' # LINE Notify API 網址
#token = '你的 LINE Notify 權杖' # 自己申請的 LINE Notify 權杖
token = 'A4wwPNh2WqB7dlfeQyyIAwtggn1kfZSI5LkkCdia1gB'
headers = {
'Authorization': 'Bearer ' + token # POST 使用的 headers
}
for i in rts: # 讀取串列的每個項目
try: # 使用 try 避開最後一行的空白行
a = i.split(',') # 每個項目用逗號拆分成子串列
print(a[0] + ': ' + a[12]) # 取出第一個 ( 0 ) 和第十三個項目 ( 12 )
#--------------------------------------------------------------------
client.publish("alex9ufo/ratetbot",a[0] + ': ' + a[12])
#--------------------------------------------------------------------
data = {# 發送的訊息
'message':'Python送出 目前台灣銀行牌告匯率 -->幣別 現金 '+ a[0] + ': ' + a[12]
}
data = requests.post(url, headers=headers, data=data) # 發送 LINE NOtify
time.sleep(5) # wait
#--------------------------------------------------------------------
except:
break
#============MQTT===================#
client.loop_stop() #stop the loop
#============Line Notify===================#
沒有留言:
張貼留言