구글 검색결과 링크를 가져오려면
http를 이용해 구글 검색 url로 접속 후 돌아온 html을 파싱해서 a태그를 추출하는 직접 파싱하는 방식과
정식 구글 API를 이용하는 방법이 있습니다. 안정성을 위해 추천하는 방법은 후자입니다.
아래는 구글 Custom Search API를 이용하는 방법에 대한 샘플입니다.
![](https://blog.kakaocdn.net/dn/dde9zE/btsIkOcKqTD/4PFqy8kvFbqnO6aInUKKTk/img.png)
먼저 Json 데이터를 파싱하기 위한 클래스로 JsonBag 클래스를 이용합니다.
위 링크에서 JsonBag Treeview.zip 파일을 다운 받아서 JsonBag.cls 파일을 압축을 풀어서 프로젝트 창으로 드래그 합니다.
![](https://blog.kakaocdn.net/dn/BHTNo/btsIlQAxH8g/a5UxtU8tKvBhgSiLt3vF61/img.png)
그 다음 구글 검색 API를 사용하기 위한 사전 준비가 좀 필요합니다.
1) https://console.cloud.google.com/apis/dashboard.' 방문해서
2) 프로젝트 생성
3) Custom Search JSON 이라는 라이브러리를 허용해야 합니다.
4) https://developers.google.com/custom-search/v1/introduction?apix=true&hl=ko 접속해서 허용해주세요.
5) '키 가져오기' 를 눌러서 API KEY를 만듭니다.
6) https://programmablesearchengine.google.com/controlpanel/create?hl=ko 방문해서
7) 자신의 검색엔진을 만들고 'cx' 코드 즉 검색엔진 ID를 받습니다.
이제 구글 API를 사용하기 위한 준비가 되었습니다.
Alt+F11 창에서 모듈을 추가하고 아래 코드를 넣고 API KEY와 검색엔진 ID를 수정 입력합니다.
Option Explicit
'Const API_KEY = "Your Google API KEY ==== 40 Chars ====="
Const API_KEY = "***************************************" '40 Chars
'Const API_ID = "12345ab567c123def" 'Search Engine ID
Const API_ID = "*****************"
'1) Visit 'https://console.cloud.google.com/apis/dashboard.'
'2) Create a project with the default name.
'3) Allow the library called 'Custom Search JSON'
'4) Vist https://developers.google.com/custom-search/v1/introduction?apix=true&hl=ko and Enable
'5) Generate your API KEY by clicking '키 가져오기' and Copy the key.
'6) Visit https://programmablesearchengine.google.com/controlpanel/create?hl=ko
'7) Greate your own search engine and copy the 'cx' code
Dim Http As Object 'MSXML2.ServerXMLHTTP60 ' Object
'Dim Html As New MSHTML.HTMLDocument
Dim JSON As New JsonBag
Sub getTopSearchResult()
Dim sht As Worksheet
Dim lastRow As Range, rng As Range
Set Http = CreateObject("MSXML2.ServerXMLHttp")
Set sht = ActiveSheet
Set lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp)
If lastRow.Row < 2 Then Exit Sub
For Each rng In sht.Range("A2:A" & lastRow.Row)
If getSearchResult(rng) = -1 Then Exit For
Next rng
sht.Columns.AutoFit
'sht.Columns("H").ColumnWidth = 100
sht.Rows.AutoFit
'Set Html = Nothing
Set Http = Nothing
End Sub
Function getSearchResult(q As Range) As Integer
Dim oSht As Worksheet
Dim sUrl As String
Dim cID$, Views$, SubCount$, Videos$, Title$, Descr$, Since$
'https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures
sUrl = "https://www.googleapis.com/customsearch/v1?key=" & API_KEY & "&cx=" & API_ID & "&num=1&q=" & q.Text
' {
' "kind": "customsearch#search",
' "url": {
' "type": "application/json",
' },
' "items": [
' {
' "kind": "customsearch#result",
' "title": "사과 - 나무위키",
' "link": "https://namu.wiki/w/%EC%82%AC%EA%B3%BC",
' "displayLink": "namu.wiki",
' "pagemap": {
' "cse_thumbnail": [
' {
' "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8EWhM6Hif1SroDjNJho-isWjNg9lPri3uUU7hBoI3zit7loQQN-k0pRk&s",
' "width": "275",
' "height": "183"
' }
' ]
' }
' }
' ]
'}
'//error
'{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","errors":[{"message":"API key not valid. Please pass a valid API key.","domain":"global","reason":"badRequest"}],"status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID","domain":"googleapis.com","metadata":{"service":"youtube.googleapis.com"}}]}}
With Http
.Open "Get", sUrl, False
.setRequestHeader "User-Agent", "Mozilla/5.0 (Linux; Android 6.0;) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36"
.setRequestHeader "Content-Type", "application/json"
.send
'Html.body.innerHTML = .responseText
JSON.JSON = .responseText
End With
'Debug.Print JSON.JSON
If JSON.Exists("error") Then
If MsgBox("[ Error!! " & JSON("error")("code") & " ] " & JSON("error")("message") & _
vbNewLine & vbNewLine & "Stop now?", vbYesNo + vbCritical) = vbYes Then
getSearchResult = -1
Else
getSearchResult = 0
End If
Exit Function
End If
Set JSON = JSON("items")(1)
Set oSht = q.Parent
q.Offset(, 1) = JSON("link")
oSht.Hyperlinks.Add q.Offset(, 1), JSON("link"), , "Jump to"
q.Offset(, 2) = JSON("title")
If JSON("pagemap")("cse_thumbnail").Count Then
q.Offset(, 3) = JSON("pagemap")("cse_thumbnail")(1)("src")
oSht.Hyperlinks.Add q.Offset(, 3), q.Offset(, 3), , "Jump to"
End If
getSearchResult = 1
End Function
이 방법도 검색 개수의 제한이 있는 단점이 있습니다.
샘플 파일을 아래 첨부합니다.
참고 1)
https://kin.naver.com/qna/detail.naver?d1id=1&dirId=102020101&docId=438370556
구글 검색 이미지탭의 첫번째 이미지의 썸네일과 원본이미지 url 을 가져...
A열에 검색을 원하는 단어를 입력 후매크로를 실행하면https://www.google.com/search?q=%EC%BB%A4%ED%94%BC&tbm=isch&ved...
kin.naver.com
위의 예시는 웹으로 접속하는 것처럼 구글 이미지검색해서 첫번째 사진을 가져오는 예시입니다.
참고2) : 구글 API를 이용한 유튜브 채널 정보 가져오기
https://konahn.tistory.com/m/entry/getYoutubeStats
엑셀에서 실시간 유튜브 구독자수 모니터링
엑셀에서 실시간으로 유튜브 채널들의 구독자수, 조회수 등을 모니터링하는 예제입니다. >> 관련: 지식인 유튜브 구독자수를 구글 API를 이용해서 가져와서 60초, 5분 등 특정 시간마다 갱신하도
konahn.tistory.com
'XLS+VBA' 카테고리의 다른 글
365 엑셀에서 셀안의 그림(PictureInCell) 기능 (0) | 2024.12.23 |
---|---|
단어의 빈도수 통계내기 (2) | 2024.12.06 |
WinHttp 한글 인코딩이 깨질 때 처리 방법(예시: 당근 사이트) (0) | 2024.11.18 |
의료기기 검색 크롤링 (2) | 2024.10.03 |
엑셀연동] 자동 방배정 및 명단 출력 2 (0) | 2024.05.23 |
엑셀연동] 방배정 명단 출력 1 (0) | 2024.05.23 |
교보문고 ISBN 도서 검색(JSON) (1) | 2024.05.15 |
모든 행 값을 랜덤으로 섞기 (1) | 2024.03.01 |
최근댓글