import requests, sys, telegram from bs4 import BeautifulSoup as bs def log_in_sir(): LOGIN_INFO = { 'url' : '%2F%2Fsir.kr', 'mb_id': 'my_id', # 아이디를 입력하세요 'mb_password': 'my_password' # 패스워드를 입력하세요 } user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' headers = {'User-Agent': user_agent} with requests.Session() as s: s.get('https://sir.kr/bbs/login.php', headers=headers) rsp = s.post('https://sir.kr/bbs/login_check.php', data=LOGIN_INFO, headers=headers) if rsp.status_code != 200: print('로그인에 실패하였습니다.') sys.exit() return s def parse_sir(s): soup1 = parse('https://sir.kr/bbs/pushmsg.php?read=n', s) lis = soup1.find('ul', {'class':'pushmsg_list'}).findAll('li') if lis[0].has_attr('id'): print('알림이 없습니다.') sys.exit() new_data = {} for l in lis: tit = l.find('span', {'class':'list_tit'}) href = l.a['href'] if l.a['href'].startswith('https:') else 'https:' + l.a['href'] comment = '' if '#c' in href: c_no = href.split('#')[-1] s2 = requests.Session() soup2 = parse(href, s2) comment = soup2.find('a', {'id':c_no}).find_next_sibling('article')\ .find('div', {'class':'vcmt_content'}).text.strip().replace('\n', ' ') msg = tit.b.text + tit.find(text=True, recursive=False).replace('\n', '') if comment: msg += f' : {comment}' new_data[msg] = href old_data = read_file() diff = list(set(new_data) - set(old_data)) send_msgs = [f'{x}\n\n{new_data[x]}' for x in diff] for s in send_msgs: telegram_bot(s) write_file(new_data) return def parse(url, s): html = s.get(url).content result = bs(html, 'html5lib') return result def read_file(): try: return [line.rstrip('\n') for line in open('sir_alarm_telegram.log', 'rt', encoding='utf-8')] except: return [] def write_file(data): with open('sir_alarm_telegram.log', 'wt', encoding='utf-8') as f: f.write('\n'.join(data)) return def telegram_bot(msg): bot = telegram.Bot(token='my_token') # 텔레그램 토큰을 입력하세요 try: chat_id = bot.getUpdates()[-1].message.chat.id except: chat_id = 1234567890 # 텔레그램 챗아이디를 입력하세요 bot.sendMessage(chat_id=chat_id, text=msg, parse_mode=telegram.ParseMode.HTML) if __name__ == '__main__': s = log_in_sir() parse_sir(s)