티스토리 뷰
스프레드시트 스크립트의 UrlFetchApp 클래스로 외부 사이트에 접근할 수 있습니다
최근 사이트들은 거의 다 유니코드 UTF-8을 기본적인 인코딩 방식으로 사용하고 있어서 일반적으로는 문제가 없는데, 일부 사이트들은 여전히 유니코드를 지원하지 않고 EUC-KR(CP949, MS949) 같은 다른 인코딩을 사용해서 한글이 깨져 보이는 문제가 있습니다
네이버 카페도 1년전까지만 해도 일부 페이지들은 MS949 인코딩을 사용하고 있었으나 지금은 UTF-8로 바뀌었습니다
아래 Fetch함수로 서버 페이지를 가져왔는데 한글이 깨진다면 브라우저에서 해당 페이지가 어떤 인코딩 형식을 쓰는지 확인하시고 인코딩 형식을 설정하시면 됩니다
참고로 스크립트에서 UrlFetchApp 사용시 요청할때 아니라, getContentText()로 결과를 읽을때에도 인코딩 형식을 지정해야 됩니다
getContentText() 함수는 UTF-8로 변환된 문자열을 반환합니다
스프레드시트에서 UrlFetchApp 사용시 외부 사이트 접근 권한을 허용해주어야 됩니다
기본 함수
/**
* @description URL 주소의 데이터를 가져온다
* @param {String} method 요청 방식 = [ "get" | "post" ]
* @param {String} url 주소
* @param {String} contentType 컨텐츠 유형 = [ "json" | "text" | "form" ]
* form : key=value 형식
* json : JSON 형식
* text : 일반 text/html 형식
* @param {Object} headers 요청 헤더 = {
* Cookie: {String}, // 쿠키
* Referer: {String}, // 리퍼러
* ...
* }
* @param {Object} payload 요청 본문. POST 요청시 데이터
* @param {String} encoding 인코딩 형식 = [ null | "UTF-8" | "CP949" | "MS949" | ... ]
* @returns {string} 응답 텍스트
*/
function Fetch(method, url, contentType = 'text', headers = null, payload = null, encoding = null)
{
const options = {
method: method,
headers: headers || {}
};
contentType = contentType.toLowerCase()
if (contentType == 'json') {
options.contentType = 'application/json';
if (typeof payload != 'string') {
payload = JSON.stringify(payload);
}
} else if (contentType == 'form') {
options.contentType = 'application/x-www-form-urlencoded';
} else {
options.contentType = 'text/html';
}
if (method.toLowerCase() == 'post' && payload) options.payload = payload;
if (encoding) options.contentType += '; charset='+ encoding;
try {
var r = UrlFetchApp.fetch(url, options);
if (r.getResponseCode() == 200) {
return r.getContentText(encoding);
} else {
Logger.log('[ERROR] Fetch() HTTP 응답 코드 오류: ' + response.getResponseCode());
}
} catch(e) {
Logger.log('[ERROR] Fetch() 데이터 불러오기 오류: ' + e.toString())
}
return '';
}
사용 예시
1. GET 요청
const COOKIE = '쿠키 내용';
function testGetList(page, listCount = 30) {
let r = Fetch(
'get',
`url주소?page=${page}&count=${listCount}`,
'text',
{
Cookie: COOKIE,
Referer: 'url주소'
}
)
Logger.log(r)
return JSON.parse(r);
}
2. POST 요청
1. 폼 데이터 형식 (Key=Value)
const COOKIE = '쿠키 내용';
function testPostList(page, listCount = 30) {
let r = Fetch(
'post',
`url주소`,
'form',
{
Cookie: COOKIE,
Referer: 'url주소'
},
{
page: page,
count: listCount
}
)
Logger.log(r)
return JSON.parse(r);
}
2. JSON 형식
const COOKIE = '쿠키 내용';
function testPostList(page, listCount = 30) {
let r = Fetch(
'post',
`url주소`,
'json',
{
Cookie: COOKIE,
Referer: 'url주소'
},
{
page: page,
count: listCount
}
)
Logger.log(r)
return JSON.parse(r);
}
POST 요청 테스트를 할 수 있는 테스트 서버 사이트
https://posttestserver.dev/
PostTestServer.dev
Open Box Open Random Box What is this? PostTestServer.dev a simple post test server that allows you to post data to a box and then retrieve it later. This is useful for testing forms, webhooks, and other services that require a public endpoint. How does it
posttestserver.dev
- 섬네일 이미지 생성 : Copilot
'프로그래밍 > 스프레드시트' 카테고리의 다른 글
| [스프레드시트] 유튜브 조회수 크롤링 하는 방법 (0) | 2025.10.18 |
|---|---|
| [스프레드시트] 문자열 중에서 데이터에 해당하는 문자 추출하기 (RegExExtract) (0) | 2025.09.26 |
| [스프레드시트] 금액 단위를 숫자로 풀어주는 사용자 함수 만들기 (3) | 2025.07.29 |