본문 바로가기
라즈베리파이

셰익스피어 문장을 10초마다 무작위로 가져오는 Python 코드

by 할10000 2023. 12. 2.
import requests
import time
from bs4 import BeautifulSoup
import random
import RPi.GPIO as GPIO

GPIO_PIN = 17
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_PIN, GPIO.OUT)
url = "https://www.opensourceshakespeare.org/views/plays/play_view.php?WorkID=othello&Scope=entire&pleasewait=1&msg=pl"

try:
    while True:
        # 웹페이지에서 데이터 가져오기 (UTF-8 인코딩 설정)
        response = requests.get(url)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')

        # 문장 추출 (예시: <p> 태그 사용)
        sentences = soup.find_all('p')
        if sentences:
            random_sentence = random.choice(sentences).text.strip()
        
            GPIO.output(GPIO_PIN, GPIO.HIGH)
            print(random_sentence)
            time.sleep(10)
            GPIO.output(GPIO_PIN, GPIO.LOW)
        else:
            print("Cannot find Sentence.")
            time.sleep(10)
        
except KeyboardInterrupt:
    print("EXIT...")
except Exception as e:
    print(f"ERROR DETECTIVE!!!: {str(e)}")
finally:
    GPIO.cleanup()

'라즈베리파이' 카테고리의 다른 글

라즈베리 파이 설치  (0) 2023.11.29