rs.execute(''' select url, Name, writeDate from chejuList1 ''') items = rs.fetchall() for item in items: print(item[0] + ' ' + item[1]) response = requests.get(item[0]) bs = BeautifulSoup(response.text, 'html.parser') text1 = re.sub('(<([^>]+)>)', '', bs.get_text()) tt = '' for line in text1.split('\n'): if line.strip() != '': print(re.search(regex, line.strip())) #break
일단 할 수 있는 것은 다음 검색에서 제주맛집 을 찾아보자... 그리고 이제 그것을 스크랩해서 제주도에 있는 맞집 리스트를 만들어 보는 것이다. 블로거 들이 작성한 것이기 떄문에 나름 검증은 되었다고 봐도 될 듯 하고, 그 리스트를 잘 정리하면 중복 되는 것도 있을 꺼고... 그렇게 해서 나만의 맛집 목록을 만들어 보는 것이다.
옆집(?)에 잠시 가 보면 안드로이드에서 하는 메시지 보내는 것에 대한 이야기가 있으니 참고...
import firebase_admin from firebase_admin import credentials from firebase_admin import db from firebase_admin import messaging import datetime
#Firebase database 인증 및 앱 초기화 cred = credentials.Certificate('./services_firebase.json') firebase_admin.initialize_app(cred,{ 'databaseURL' : 'https://my-.........firebasedatabase.app/' })
def mesgSend(token): registration_token = token
# See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title='$GOOG up 1.43% on the day', body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.', ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342' ), ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), data={ 'URL':'https://billcorea.tistory.com', 'BODY':'message is Body' }, #topic='allDevices', token=registration_token, )
# Send a message to the device corresponding to the provided # registration token. response = messaging.send(message) # Response is a message ID string. print('Successfully sent message:', response)
userInfo = db.reference('UserInfo') #print(type(userInfo.get())) for val in userInfo.get().values(): mesgSend(val['userToken'])
소스에 대한 이해는 나중에 하고, 일단 따라해 보자면.
위에 대한 소스를 작성을 해서 해 보면 된다. 소스를 보면서 준비를 해 보자...
1. 서버 인증서 만들기
./services_firebase.json 이 파일이 있으면 인증서를 대신할 수 있다. 이건 어디서 얻는 것인가 ? firebase의 console 에서 프로젝트 설정을 가면 서비스 계정이라고 탭이 있고 거기서 새 비공개키 생성 을 클릭 하면 자동으로 생성이 되는 json 파일 있다. 그 파일의 이름은 프로젝트 이름을 따라서 생성이 되기 때문에 길다... 그걸 좀 줄였다. 이 파일은 android 개발할 때도 받았던 파일 이였다. 같은 걸 쓰면 될 것을...
firebase 서버키를 받아보자
2. 메시지 수신할 상대방을 어떻게 알 것인가 ?
안드로이드 개발페이지 에서 기술한 것 처럼 topic 을 구독하는 방식을 구현 했다면 topic 으로 전달 할 수 있고, 그렇지 않다면 개발 기기 마다 등록한 token 을 알아야 한다. 그래서 이 소스에서는 firebase의 realtime database 에 userInfo 라는 정보에 그런 정보가 있다는 가정하에 코드를 작성하였다. 그래서 userInfo 라는 realtime database 을 읽어서 userToken을 받아오는 부분이 기술 되어 있다.
userInfo = db.reference('UserInfo') #print(type(userInfo.get())) for val in userInfo.get().values(): mesgSend(val['userToken'])
이부분에서 databaseURL 은 어디서 가져 왔는 가 ? firebase의 console 에서 realtime database 을 클릭해 보면 처음 화면에 아래 그림 처럼 https://... 으로 시작하는 URL 이 기술 되어 있으니 그걸 복사해서 붙이면 끝.
database URL
3. 메시지 보내기
이제 token 도 얻어 왔으니 (실제 얻어 오는 건 안드로이드 개발 부분에서 참고 하시길 ...) 메시지를 보내 보자. function 으로 define 해 두면 나중에 복사해 쓰기 쉬우니... 이렇게 코드를 작성했다. 여기서 token 은 userInfo 에서 얻어온 것이고... 아래 부분은 잘 알 수도 있지만, notification 에 있는 건 안드로이드 폰에 알림창에 표시되는 내용이고
androidConfig 는 잘 모르겠지만, 안드로이드에서 보여줄 때 사용될 설정인 것 같고, 아래 data= 에 들어가는 건, 자기가 개발하는 앱에 전달할 데이터 부분으로 사용하면 될 것 같다.
def mesgSend(token): registration_token = token
# See documentation on defining a message payload. message = messaging.Message( notification=messaging.Notification( title='$GOOG up 1.43% on the day', body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.', ), android=messaging.AndroidConfig( ttl=datetime.timedelta(seconds=3600), priority='normal', notification=messaging.AndroidNotification( icon='stock_ticker_update', color='#f45342' ), ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(badge=42), ), ), data={ 'URL':'https://b.............com', 'BODY':'message is Body' }, #topic='allDevices', token=registration_token, )
# Send a message to the device corresponding to the provided # registration token. response = messaging.send(message) # Response is a message ID string. print('Successfully sent message:', response)
4. 마치며.
음... 그런데, 아쉽게도 windows 에서는 검증을 해 보지 못했다. firebase_admin 패키지를 설치해야 하는데, windows11 에 python 3.9 을 설치한 지금은 이상하게도 firebase_admin 패키지 설치가 되지 않는다. 이유는 아직 모른다. 그래서 linux 가 설치된 rasberry pi 3B 을 이용해서 확인했고, 전달이 잘 되는 것도 확인 했다.
메시지 보내는 화면
이번에는 폰에 메시지가 도착하고 확인하는 예제 화면을 잠시 ... 감상(?)하는 것으로 마무리...
#스하리1000명프로젝트, Terkadang sulit untuk berbicara dengan pekerja asing, bukan? Saya membuat aplikasi sederhana yang membantu! Anda menulis dalam bahasa Anda, dan orang lain melihatnya dalam bahasa mereka. Ini menerjemahkan secara otomatis berdasarkan pengaturan. Sangat berguna untuk obrolan mudah. Lihatlah ketika Anda mendapat kesempatan! https://play.google.com/store/apps/details?id=com.billcoreatech.multichat416
글목록은 얻어오는 방법은 티스트로 api 가이드를 참고해 보면 알 수 있다. 몇 번 해 본 것들이니 따로 설명은 생략.
3. 이제 소스 작업을 해 보자.
#coding=utf-8 import json import sqlite3 import time
import pyperclip import requests from urllib import parse from selenium import webdriver from selenium.webdriver import ActionChains, Keys from selenium.webdriver.common.by import By
conn = sqlite3.connect("test.sqlite", isolation_level=None) rs = conn.cursor() rs.execute("CREATE TABLE IF NOT EXISTS myUrlList \ (id integer PRIMARY KEY, url text, Name text, writeDate text)")
반복적으로 하고 있는 것이기는 하지만, 아직도 좀 힘든 부분은 access_token을 얻어 오는 것이다. 전체 스크립트를 기술해 두었지만, #1 print(getUrl) 을 최종적으로 막았지만, print(getUrl) 에서 출력되는 링크를 클릭해 들어가면 code 값을 얻을 수 있고, #2 getToken() 으로 막았지만, 저걸 풀고 getToken() 을 실행해 보면 access_token 을 얻을 수 있다.
access_token 은 한번 얻고 나면 변경할 필요가 없는 것 같아서. 그다음부터는 위에서 처럼 #1, #2는 막아 두고 진행을 해도 된다.
4. 그다음은 post 리스트를 얻어오는 링크를 실행해서 티스토리의 post 목록을 받아오고,
5. 필요에 따라 카테고리 값을 구분해서 필요한 부분만 선택해서 네이버 블로그에 저장하는 처리를 진행한다.
6. 진행하기 전에 네이버 내 정보에 들어가서 보안설정 - 2단계 인증 관리에서 애플리케이션 비밀번호 관리를 통해 파이썬 스크립트에서 사용할 비밀번호를 하나 생성한 다음 위의 스크립트를 진행해야 한다. 그렇지 않으면 자동화 스크립트에서 로그인하는 것을 네이버는 싫어해서 그림 캡챠를 돌려 로그인을 방해(?)하는 처리를 하고 있다.
네이버 2단계 인증
7. 이렇게 하면 짜잔... 티스토리에 작성한 글들의 전체 본문은 아니지만 링크를 달아서 네이버 블로그에 다 담아 볼 수 있다. ㅎㅎㅎ
인스타 그램에 사진 올리기를 해 보기로 했다. 음... 365일 24시간 구동해야 하는 컴터가 있으면야 좋기는 하겠지만,
우리에게는 rasberrypi 가 있으니 그것으로 대신해 보기로 한다. 그래야 camera 도 사용할 수 있으니 말이다.
그리고 내게는 작은 어항에 살고 있는 반려 거북이도 하나 있으니 말이다. 일단 코드는 아래오 같이 구현 했다.
from instabot import Bot import os import shutil import picamera
def clean_up(): dir = "config" remove_me = "file.jpg.REMOVE_ME" # checking whether config folder exists or not if os.path.exists(dir): try: # removing it so we can upload new image shutil.rmtree(dir) except OSError as e: print("Error: %s - %s." % (e.filename, e.strerror)) if os.path.exists(remove_me): src = os.path.realpath("file.jpg") os.rename(remove_me, src)
def upload_post(): camera = picamera.PiCamera() camera.capture('file.jpg')
#billcorea #운동동아리관리앱 🏸 Schneedle, aplikasi yang wajib dimiliki oleh klub bulu tangkis! 👉 Match Play – Rekam Skor & Temukan Lawan 🎉 Sempurna untuk di mana saja, sendirian, bersama teman, atau di klub! 🤝 Jika Anda suka bulu tangkis, cobalah