今天就只針對前幾篇做個總結,以及成果的展示,
算是來偷懶一下XDDD,(雖然每篇都在拖>////<
import os
import requests
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from datetime import datetime
line_bot_api = LineBotApi('阿彌陀佛')
handler = WebhookHandler("阿彌陀佛")
@csrf_exempt
def callback(request):
if request.method == 'POST':
signature = request.META['HTTP_X_LINE_SIGNATURE']
body = request.body.decode('utf-8')
try:
handler.handle(body, signature)
except InvalidSignatureError:
messages = (
"Invalid signature. Please check your channel access token/channel secret."
)
logger.error(messages)
return HttpResponseBadRequest(messages)
return HttpResponse("OK")
@handler.add(event=MessageEvent, message=TextMessage)
def handl_message(event):
outInfo = crawler("content")
message = TextSendMessage(text=outInfo)
line_bot_api.reply_message(
event.reply_token,
message)
def crawler(content):
chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
chrome_options.add_argument("--headless") #無頭模式
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--no-sandbox")
driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
driver.get("https://www.cwb.gov.tw/V8/C/W/Town/Town.html?TID=1000806")
Temp = driver.find_element_by_id('GT_C_T').text #現在溫度
bodyTemp = driver.find_element_by_id('GT_C_AT').text #體感溫度
RelativeHumidity = driver.find_element_by_id('GT_RH').text #相對溼度
Rain = driver.find_element_by_id('GT_Rain').text #降雨量
Sunrise = driver.find_element_by_id('GT_Sunrise').text #日出時間
Sunset = driver.find_element_by_id('GT_Sunset').text
driver.quit()
time = datetime.now()
timeprint = datetime.strftime(time,"%Y/%m/%d %H:%M")
content="【名間鄉當前天氣概況】"+"\n"+"\n"+"現在溫度 : "+Temp+"°C"+"\n"+"體感溫度 : "+bodyTemp+"°C"+"\n"+"相對溼度 : "+RelativeHumidity+"%"+"\n"+"降雨量 : "+Rain+"mm"+"\n"+"日出時間 : "+Sunrise+"\n"+"日落時間 : "+Sunset + "\n"+"現在時間為:"+timeprint
# content = "現在溫度:%s 體感溫度:%s 相對溼度:%s 降雨量:%s 日出時間:%s 日落時間:%s"%(Temp, bodyTemp, RelativeHumidity, Rain, Sunrise, Sunset)
# content= {
# "現在溫度":Temp,
# "體感溫度":bodyTemp,
# "相對溼度":RelativeHumidity,
# "降雨量":Rain,
# "日出時間":Sunrise,
# "日落時間":Sunset
# }
# print(content)
return content
改成這樣之後重新上傳,
成果如下~
這樣天氣狗就正式上線啦~
對了,如果爬蟲還是有相關問題的話,
可以看看這篇影片唷~
裡面有更詳細的關於如何在heroku上使用selenium的講解~
今天是 美秀集團 的 擋一根 網址如下~~~
https://www.youtube.com/watch?v=3_GFxZ9xA7o&list=PLZ_d6NX2sE81xaPTSSsKeiF_7r3EgyjAg&index=87