簡易物聮網系統實作(2)
-
本單元重點在於引導學生使用Python程式將教師架設的客製化網站爬取資料,並依資料內容作相對應的輸出反應。
#!/usr/bin/python #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ #|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w| #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # Copyright (c) 2016, raspberrypi.com.tw # All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # led_blink.py # Blinking led without warning (Add try/except) # # Author : sosorry # Date : 06/22/2014 import RPi.GPIO as GPIO import time import requests from bs4 import BeautifulSoup LED_PIN = 12 GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN, GPIO.OUT) url = "http://127.0.0.1:8000" r = requests.get(url) web_content = r.text soup = BeautifulSoup(web_content, 'html.parser') content = soup.find_all('div', class_="value") values = [int(e.text) for e in content] print(values[0]) try: while values[0]>30: print("LED is on") GPIO.output(LED_PIN, GPIO.HIGH) time.sleep(1) print("LED is off") GPIO.output(LED_PIN, GPIO.LOW) time.sleep(1) except KeyboardInterrupt: print("Exception: KeyboardInterrupt") finally: GPIO.cleanup()