ChatGPT4-o를 이용해서 엑셀 사용자 정의 함수(UDF)를 만들어 보자.
뉴스 URL을 가져오는 사용자 정의함수는 예전에 만들어놨는데,
뉴스 URL에 해당하는 뉴스 본문 전체도 가져 오고 싶어 졌다.
처음부터 코딩하는건 귀찮고.. ChatGPT에게 코드를 만들어 달라고 했다.
프롬프트
넌 엑셀 vba 개발자야. 신문 기사 url을 인수로 받아서, url에서 기사 제목과 기사 본문을 배열로 리턴하는 사용자 정의 함수를 만들어줘. 함수 정의 function importNews(sURL as string) as variant 리턴받을 변수 : sResult() sResult의 필드 : 기사제목, 기사 본문, 기자 이름, 입력 및 수정, URL 예제 URL : https://n.news.naver.com/mnews/article/277/0005438348?sid=104 기사 제목 : 오픈AI, 美 타임지와 콘텐츠 사용 계약 "챗GPT 업그레이드" 입력 및 수정 : 입력2024.06.28. 오전 8:44 수정2024.06.28. 오전 8:45 기자 이름 : 김진영 기자 기사 본문 : 챗GPT 성능 향상을 위해 저명한 언론사들과 파트너십을 맺어온 오픈AI가 글로벌 주간지 타임지와도 손을 잡았다. 27일(현지시간) 오픈AI는 자사 홈페이지에 "챗GPT를 포함한 오픈AI의 제품에 타임지의 신뢰할 수 있는 저널리즘을 .......... (이하 생략) |
GPT답변
엑셀 VBA에서 신문 기사 URL을 받아서 기사 제목, 기사 본문, 기자 이름, 입력 및 수정 날짜, URL을 배열로 반환하는 함수를 만드는 방법을 아래에 작성했습니다. 이 코드는 URL에서 HTML 콘텐츠를 가져와서 필요한 정보를 추출합니다. |
Function importNews(sURL As String) As Variant Dim http As Object Dim html As Object Dim sResult(1 To 5) As String Dim title As String Dim body As String Dim reporter As String Dim dates As String
' Create the necessary objects for HTTP request and HTML document Set http = CreateObject("MSXML2.XMLHTTP") Set html = CreateObject("HTMLFile")
' Send the HTTP request http.Open "GET", sURL, False http.send
' Wait for response Do While http.readyState <> 4 DoEvents Loop
' Load the response HTML html.body.innerHTML = http.responseText
' Extract the article title On Error Resume Next title = html.getElementsByClassName("media_end_head_headline").Item(0).innerText On Error GoTo 0
' Extract the article body On Error Resume Next body = html.getElementsByClassName("media_end_body").Item(0).innerText On Error GoTo 0
' Extract the reporter name On Error Resume Next reporter = html.getElementsByClassName("byline").Item(0).innerText On Error GoTo 0
' Extract the dates On Error Resume Next dates = html.getElementsByClassName("media_end_head_info_datestamp").Item(0).innerText On Error GoTo 0
' Assign the extracted values to the result array sResult(1) = title sResult(2) = body sResult(3) = reporter sResult(4) = dates sResult(5) = sURL
' Return the result array importNews = sResult End Function |
이 함수는 다음 단계를 따릅니다:
이 코드를 엑셀 VBA 편집기에 붙여넣고 사용하면 주어진 URL에서 필요한 정보를 추출할 수 있습니다. URL에 따라서 클래스 이름이 다를 수 있으니, 필요한 경우 해당 클래스 이름을 수정해야 합니다. |
VBE창에 모듈을 추가하고, 코드를 붙여넣은 다음에
워크시트에서 함수를 실행해본 결과.. 본문을 빼고는 꽤 잘 가져왔다.
=importNaverNews("https://n.news.naver.com/mnews/article/277/0005438348?sid=104")
본문 가져오는 코드를 보니, class명이 잘 못 지정되어있어서 아래와 같이 수정해줬다.
수정전
body = html.getElementsByClassName("media_end_body").Item(0).innerText
수정후
body = html.getElementsByClassName("newsct_article _article_body").Item(0).innerText
이제 본문도 잘 가져온다.
이제..
네이버 신문말고다른 신문도 해보자~