코딩 / / 2022. 12. 27. 15:20

[Chat GPT와 코딩!] 코드 입력, 조회, 파일다운까지 자동으로 코딩하기

반응형

썸네일

 

새로운 프로젝트를 만들기 위해서 데이터를 모으는 중이다. 데이터를 얻기위해 선택한 사이트는 보건의료 빅데이터 개방 시스템. 여기서 데이터를 하나씩 받아 합칠 생각이다.

 

 

보건의료빅데이터개방시스템

상단 메뉴영역 전체메뉴 Home 의료통계정보 질병/행위별 의료 통계 질병 세분류(4단 상병) 통계 진료받은 모든 질병에 대한 통계를 1만 2천개의 한국표준질병ㆍ사인분류의 세분류로 조회하는 서

opendata.hira.or.kr

 

 

 

 

 

 

계획은 이렇다

과정1과정2
과정3과정4
과정5

심플하게 5가지 스텝을 컴퓨터가 자동으로 수행하게 하면 된다.

 

일단 클릭할 녀석들의 아이디를 알아두자

검사

 
 

프로그램이 사이트의 특정 부분을 인식하려면 위치를 지정해주어야한다. 

주로 우클릭 - 검사를 통해 보거나 Ctrl+Shift+C를 통해서 볼 수 있다. 여기서 selector를 복사하면 CSS_SELECTOR를 사용하는 것이고 XPath, ID 등의 방법도 사용할 수 있다. 시험해본 결과 제일 잘 되는건 ID이지만 모든 항목에 ID가 있지는 않기 때문에 주로 직관적인 CSS_SELECTOR를 사용하게 된다. 그건 이후에 코드에 나타난다.

 

 

Chat GPT와 상담

질문
일단 최대한 영어로 물어본다
대답

from selenium import webdriver
from selenium.webdriver.common.by import By

# Replace with the path to your web driver
driver = webdriver.Chrome('/path/to/chromedriver')

# Navigate to the website
driver.get('https://www.example.com')

codes = ['A00', 'A01', 'A02', 'A03', 'A04', 'A05']

for code in codes:
    # Click the search button
    driver.find_element(By.ID, 'searchPopup').click()

    # Enter the code in the input field
    driver.find_element(By.ID, 'searchWrd1').send_keys(code)

    # Click the search button
    driver.find_element(By.ID, 'searchBtn1').click()

    # Click the first object on the list
    driver.find_element(By.CSS_SELECTOR, '#tab1 > section.dictionary-list-wrap > table > tbody > tr:nth-child(1) > td:nth-child(1) > a').click()

    # Click the view button
    driver.find_element(By.CSS_SELECTOR, '#ext-gen1645 > table > tbody > tr > td > div.dt-btn-search').click()

    # Wait for the page to load
    driver.implicitly_wait(10)

    # Click the download button
    driver.find_element(By.CSS_SELECTOR, '#panel-1104-body > div:nth-child(3) > div.dock_inner > div.dock_title.doc_title_selected.mec-report-titlebar > div.dock_title_btnarea > div.dock_button.dock_exp_excel_button').click()

    # Wait for the download to complete
    driver.implicitly_wait(10)

# Close the browser
driver.quit()

대답2

 

 

 

Chat GPT가 기본적인 틀을 전부 만들어놓았다. 당연히 한방에 돌아가지는 않는다. 일단 하나씩 차근차근 수정하자. 

 

질문2
질병코드 조회를 누르면 팝업이 나온다는 점을 까먹어서 클릭하자마자 창이 꺼진다. 수정하자.

from selenium import webdriver
from selenium.webdriver.common.by import By

# Replace with the path to your web driver
driver = webdriver.Chrome('/path/to/chromedriver')

# Navigate to the website
driver.get('https://www.example.com')

codes = ['A00', 'A01', 'A02', 'A03', 'A04', 'A05']

for code in codes:
    # Click the search button
    driver.find_element(By.ID, 'searchPopup').click()

    # Switch to the popup window
    driver.switch_to.window(driver.window_handles[1])

    # Enter the code in the input field
    driver.find_element(By.ID, 'searchWrd1').send_keys(code)

    # Click the search button
    driver.find_element(By.ID, 'searchBtn1').click()

    # Click the first object on the list
    driver.find_element(By.CSS_SELECTOR, '#tab1 > section.dictionary-list-wrap > table > tbody > tr:nth-child(1) > td:nth-child(1) > a').click()

    # Click the view button
    driver.find_element(By.CSS_SELECTOR, '#ext-gen1645 > table > tbody > tr > td > div.dt-btn-search').click()

    # Wait for the page to load
    driver.implicitly_wait(10)

    # Click the download button
    driver.find_element(By.CSS_SELECTOR, '#panel-1104-body > div:nth-child(3) > div.dock_inner > div.dock_title.doc_title_selected.mec-report-titlebar > div.dock_title_btnarea > div.dock_button.dock_exp_excel_button').click()

    # Wait for the download to complete
    driver.implicitly_wait(10)

    # Close the popup window
    driver.close()

    # Switch back to the main window
    driver.switch_to.window(driver.window_handles[0])

# Close the browser
driver.quit()

대답2

 
 

driver.switch_to.window(driver.window_handles[1]) 

0이면 첫번째, 1이면 팝업으로 생긴 두번째, 거기서 팝업이 또 생기면 2,3 이렇게 넘어가나보다. 클릭 한 뒤 팝업으로 컴퓨터의 시선을 움직이는 코드인가보다.

 

 

Chat GPT로 해결이 안되었던 문제, iframe

과정4
질문3

아무리 해도 프로그램이 '조회'버튼을 찾지 못한다. 계속해서 TimeoutException error이 난다. 

대답3

물어봐도 로딩될때까지 기다리라는 말 뿐이다. 이 부분에서 상당히 해맸다. 고민 끝에, 이 부분은 구글에 검색해보니 답이 나왔다. 

 

 

[Python/Selenium] Selenium으로 click( ) 하다가 안될 때는 iframe을 전환해야 한다(ft. NoSuchElementException)

안녕하세요, 왕초보 코린이를 위한 코딩유치원에 오신 것을 환영합니다. 코딩유치원에서는 파이썬 기초부터 사무자동화, 웹크롤링, 데이터 분석, 머신러닝 등의 다양한 패키지까지 초보자도 알

coding-kindergarten.tistory.com

클릭이 아닌 이유는 다름아닌 iframe이라는 놈때문이란다. 당장 찾아보았다.

 

iframe
역시나, 나도 있었다.

 
 

iframe

'페이지 안의 페이지'라는 뜻의 inline frame의 약자이다. 사실상 팝업창 처럼 별개의 페이지이기 때문에 다시한번 컴퓨터의 시선을 이동시켜주어야 했던 것이다. 

 
 

driver.switch_to.frame(driver.find_element())

switch_to.window()와 똑같다. CSS_SELECTOR를 이용해 해당 프레임으로 이동해주는 것이다. 

 

 

조회가 완료되고 다운이 완료될때까지 기다리기

아무래도 건강보험 사이트에서 질병을 조회하는거다보니 로딩이 오래걸린다. 성질급한 셀레니움 프로그램은 로딩이 안되면 바로 창을 꺼버리고 timeouterror을 내비치기 때문에 '기다려' 명령을 해주어야 한다. 거기서 사용되는 것이 explicit wait와 implicit wait이다. 

 

 

 

 

 

 
 

Explicit Wait : 특정 상황이 나타날 때까지 기다리는 것.

사용 방법 : WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, 'searchWrd1')))

element가 클릭이 가능해질 때까지 최대 10초간 기다린다는 뜻. 입맛대로 다양한 상황을 가정하고 쓸 수 있다. 

  • title_is
  • title_contains
  • presence_of_element_located
  • visibility_of_element_located
  • visibility_of
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • text_to_be_present_in_element_value
  • frame_to_be_available_and_switch_to_it
  • invisibility_of_element_located
  • element_to_be_clickable
  • staleness_of
  • element_to_be_selected
  • element_located_to_be_selected
  • element_selection_state_to_be
  • element_located_selection_state_to_be
  • alert_is_present
 
 

Implicit wait : 깡으로 몇초 기다리는 것

사용방법 : driver.implicitly_wait(10) 일단 10초 기다리기

다른 방법으로는 time.sleep(10)이 있다. 이 경우 코드 맨 위에 import.time을 해주어야한다. 

 

결과물
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Replace with the path to your web driver
driver = webdriver.Chrome()

# Navigate to the website
driver.get('http://opendata.hira.or.kr/op/opc/olap4thDsInfo.do')
codes = ['A20', 'A21', 'A22', 'A23', 'A24', 'A25', 'A26', 'A27', 'A28', 'A30', 'A31', 'A32', 'A33', 'A34', 'A35', 'A36', 'A37', 'A38', 'A39', 'A40', 'A41', 'A42', 'A43', 'A44', 'A46', 'A48', 'A49', 'A50', 'A51', 'A52', 'A53', 'A54', 'A55', 'A56', 'A57', 'A58', 'A59', 'A60', 'A63', 'A64', 'A65', 'A66', 'A67', 'A68', 'A69', 'A70', 'A71', 'A74', 'A75', 'A77', 'A78', 'A79', 'A80', 'A81', 'A82', 'A83', 'A84', 'A85', 'A86', 'A87', 'A88', 'A89', 'A90', 'A91', 'A92', 'A93', 'A94', 'A95', 'A96', 'A98', 'A99']

for code in codes:

    # Click the search button
    driver.find_element(By.ID, 'searchWrd').click()

    # Switch to the popup window
    driver.switch_to.window(driver.window_handles[1])
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, 'searchWrd1')))

    # Enter the code in the input field
    #driver.find_element(By.NAME, 'searchWrd1').click()
    driver.find_element(By.ID, 'searchWrd1').send_keys(code)

    # Click the search button
    driver.find_element(By.ID, 'searchBtn1').click()

    # Click the first object on the list
    driver.find_element(By.CSS_SELECTOR, '#tab1 > section.dictionary-list-wrap > table > tbody > tr:nth-child(1) > td:nth-child(1) > a').click()

    # Switch to the main window
    driver.switch_to.window(driver.window_handles[0])

    # 버튼이 안보이는 경우 iframe으로 들어가서 버튼을 클릭해야 함
    time.sleep(1)
    driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, 'body > section.container > section:nth-child(4) > div.olap-box > iframe'))
    WebDriverWait(driver, 200).until(EC.presence_of_element_located((By.CSS_SELECTOR,'#ext-gen1645 > table')))

    # Click the view button
    driver.find_element(By.CSS_SELECTOR,'#ext-gen1645 > table > tbody > tr > td > div.dt-btn-search > span').click()
    WebDriverWait(driver, 500).until(EC.invisibility_of_element_located((By.ID, 'm-mec-loader')))
    
    time.sleep(25)
    
    driver.find_element(By.CSS_SELECTOR, '#panel-1104-body > div:nth-child(1) > div.dock_inner > div.dock_title.doc_title_normal.mec-report-titlebar > div.dock_title_btnarea > div.dock_button.dock_exp_excel_button').click()
    time.sleep(10)
    driver.refresh()

# Close the browser
driver.quit()

 

그 결과 자기가 알아서 다운로드를 수행하는 프로그램이 완성되었다. 질병코드를 리스트에 넣으면 알아서 받아준다. 문제는 시간이 너무 느리다는 점 정도이다. 

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유