반응형
python을 이용해서 공공 DataPortal 에서 제공하는 api 및 파일데이터 목록을 가져와 파일로 저장하는것을 만들어 봤습니다.
공공DataPortal에 접속해서 3000페이지가 넘는걸 일일이 클릭하기가 힘들어
python 공부도 해볼겸해서 만들어 봤습니다.
python에서 사용한 모듈은 BeautifulSoup 과 Selenium 입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import re from selenium import webdriver from bs4 import BeautifulSoup def getHtmlFromScript(script): driver.execute_script(script) html = driver.page_source return html coptions = webdriver.ChromeOptions() coptions.add_argument( 'headless' ) coptions.add_argument( 'window-size=1920x1080' ) coptions.add_argument( "disable-gpu" ) coptions.add_argument( "user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" ) driver = webdriver.Chrome( 'c:\\dev\\chromedriver.exe' , options = coptions) / / dataType = "DATA" / / 파일데이터 dataType = "OPENAPI" / / 오픈API result = open (dataType + "_result.txt" , mode = "w" , encoding = "UTF-8" ) html = getHtmlFromScript( "doIndexSearch('%s')" % dataType) soup = BeautifulSoup(html, 'html.parser' ) items = soup.select( "div.data-item" ) lastPage = soup.find( "ul" , attrs = { "class" : "pagination" }) lastPageNumberScript = list (lastPage.select( "a" ))[ - 1 ].get( "href" ) lastPageNumber = re. compile ( "\\d+" ).search(lastPageNumberScript).group() for i in range ( 1 , int (lastPageNumber) + 1 ): print ( "=========================== %s Page ===========================" % i, end = "\n" ) html = getHtmlFromScript( "javascript:doPaging(%d)" % i) soup = BeautifulSoup(html, 'html.parser' ) items = soup.select( "div.data-item" ) for item in items: print ( item.select( "div.data-title > a" )[ 0 ].text.strip() ) #print ("-"*5, item.select("div.data-title").get_text().strip(), "-"*5 ) result.write(item.select( "div.data-title > a" )[ 0 ].text.strip() + "\n" ) result.write(item.select( "div.data-desc" )[ 0 ].text.strip() + "\n" ) result.write( "\n\n" ) if i % 10 = = 0 : result.flush() result.close() |
파일이 만들어졌네요
이제 공공DataPortal에서 제공하는 api를 가지고 무엇을 만들어보면 좋을까요???
반응형
'컴퓨터관련' 카테고리의 다른 글
python 이용하여 로또 사이트 크롤링 - 당첨정보 가져오기 및 분석 (0) | 2019.03.06 |
---|---|
한개의 아이피에 여러개의 포트로 가상호스트 설정하기 - Apache 2.4 (0) | 2019.03.01 |
정규표현식... (0) | 2017.09.07 |
chmod 디렉토리만 또는 파일만 지정하기(하위디렉토리 포함) (0) | 2017.02.11 |
ffmpeg 간단한 사용법 (0) | 2017.01.27 |