위키/목록에서 코로나바이러스감염증-19 환자 숫자 정보를 갱신하는 파이썬 스크립트입니다. Pywikibot을 통해 돌아갈 수 있게 설게했습니다.
사용방법
- 우선 파이썬을 설치한 후, 시스템의 환경변수를 추가해서 커맨드 창에서 파이썬이 작동하게 설정합니다.
- 그 다음 PIP 설치방법 안내 페이지를 이용해서 PIP 패키지를 설치합니다.
- PIP를 설치했으면 커맨드 창에 pip install selenium을 입력해 selenium 패키지를 설치합니다. (데이터 크롤링용)
- (추가) 다음으로 커맨드 창에 pip install pyperclip을 입력해 pyperclip 패키지를 설치합니다. (클립보드 내용 복사용)
- 다음 링크를 이용해서 크롬 브라우저용 Chromedriver를 다운로드 받습니다. 반드시 pwb.py가 있는 곳에 chromedriver 실행 프로그램이 있어야 합니다.
- 다음 아래의 소스코드를 복사/붙여넣기 후에 pywikibot이 설치된 폴더에서 scripts/userscripts에 COVID-19_Data_Send.py로 저장합니다.(커스텀 스크립트를 저장할 수 있는 곳)
- 다 준비가 되었다면 cd C:/(Pywikibot이 설치된 카테고리) 명령어를 이용해 Pywikibot이 있는 폴더로 이동한 뒤에 커맨드 창에
> python pwb.py COVID-19_Data_Send
이라고 입력하면 작동합니다.
스크립트 소스
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pywikibot
import pyperclip
from scripts import login
import json, re, time, datetime, os
#문자열 한 자리면 0 강제삽입
def zeroinput(_str):
if len(_str) == 0:
return '00'
elif len(_str) == 1:
return '0'+_str
else:
return _str
driver = webdriver.Chrome() #chromedriver 설정
driver.get('https://www.convertjson.com/html-table-to-json.htm')
# HTML->JSON
time.sleep(0.5)
inputbox = driver.find_element_by_id('url')
inputbox.send_keys('https://www.worldometers.info/coronavirus/#countries')
driver.find_element_by_xpath('//*[@id="btnUrl"]').click()
time.sleep(5)
x= driver.find_element_by_id('selTabNum')
x.send_keys(Keys.ENTER+Keys.DOWN+Keys.ENTER)
time.sleep(0.5)
z = driver.find_element_by_id('txta')
z1 = driver.find_elements_by_class_name('fa-clipboard')[0]
z1.click()
time.sleep(2)
txt = pyperclip.paste()
print(txt)
driver.close()
dats = json.loads(txt) #json 코드로 읽기
# 일단 딕셔너리들을 모은 리스트 형태로
#위키/목록 텍스트 추출
site = pywikibot.Site('ko', 'libre')
page = pywikibot.Page(site, "Template:COVID-19/세계 통계 확진자순")
txt2 = page.text
for dat in dats:
#dats에서 dict 형태 dat 추출
country = dat['Country,\nOther'] #국적 정보
TC = dat['Total\nCases']
TD = dat['Total\nDeaths']
TR = dat['Total\nRecovered']
AC = dat['Active\nCases']
C1M = dat['Tot Cases/\n1M pop']
D1M = dat['Deaths/\n1M pop']
TT = dat['Total\nTests']
T1M = dat['Tests/\n 1M pop']
if country == 'World':
txt2 = re.sub(f'<!--{country}_TC-->'+r'[0-9,]+',\
f'<!--{country}_TC-->'+f'{TC}', txt2 )
txt2 = re.sub(f'<!--{country}_TD-->'+r'[0-9,]+',\
f'<!--{country}_TD-->'+f'{TD}', txt2 )
txt2 = re.sub(f'<!--{country}_TR-->'+r'[0-9,]+',\
f'<!--{country}_TR-->'+f'{TR}', txt2 )
txt2 = re.sub(f'<!--{country}_AC-->'+r'[0-9,]+',\
f'<!--{country}_AC-->'+f'{AC}', txt2 )
#국적 정보!
if f'<!--{country}-->' in txt2:
txt2 = re.sub(f'<!--{country}_TC-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_TC-->'+f'{TC}', txt2 )
txt2 = re.sub(f'<!--{country}_TD-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_TD-->'+f'{TD}', txt2 )
txt2 = re.sub(f'<!--{country}_TR-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_TR-->'+f'{TR}', txt2 )
txt2 = re.sub(f'<!--{country}_AC-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_AC-->'+f'{AC}', txt2 )
txt2 = re.sub(f'<!--{country}_C1M-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_C1M-->'+f'{C1M}', txt2 )
txt2 = re.sub(f'<!--{country}_D1M-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_D1M-->'+f'{D1M}', txt2 )
txt2 = re.sub(f'<!--{country}_TT-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_TT-->'+f'{TT}', txt2 )
txt2 = re.sub(f'<!--{country}_T1M-->'+r'([0-9,\.]+|N/A|\b)',\
f'<!--{country}_T1M-->'+f'{T1M}', txt2 )
#통계 작성 시점
x=datetime.datetime.now()
msg_date= '<!--date-->'+str(x.year)+'-'+str(x.month)+'-'+str(x.day)
msg_time ='<!--time-->'+zeroinput(str(x.hour))+':'+zeroinput(str(x.minute))+'(KST)'
#시간 수정
msg_date_old= '<!--date-->'+r'[0-9]{4,}\-[0-9]{1,2}\-[0-9]{1,2}'
msg_time_old= '<!--time-->'+r'[0-9]{1,2}:[0-9]{1,2}\(KST\)'
txt2=re.sub(msg_date_old, msg_date, txt2)
txt2=re.sub(msg_time_old, msg_time, txt2)
# 데이터 갱신!
#login.main()
print(txt2)
with open('COVID19.mediawiki', 'w', encoding='utf8') as g:
g.write(txt2)
page.text = txt2
page.save('봇 : COVID-19 통계 갱신')
#login.main('-logout')