실습
4.3 실습
URL의 다양한 활용 방법을 실습을 통해 알아보겠습니다.
4.3.1 Fragment에 따른 이동
URL의 fragment(#)를 사용하면 페이지 내 특정 위치로 이동할 수 있습니다.
<a href="파일명_또는_경로명?key1=value1&key2=value2#section">링크</a><a href="파일명_또는_경로명?key1=value1&key2=value2#section">링크</a><a href="002.html?key1=value1&key2=value2#one">링크</a>
<a href="002.html?key1=value1&key2=value2#two">링크</a>
<section id="one">lorem*30</section>
<section id="two">lorem*30</section><a href="002.html?key1=value1&key2=value2#one">링크</a>
<a href="002.html?key1=value1&key2=value2#two">링크</a>
<section id="one">lorem*30</section>
<section id="two">lorem*30</section>4.3.2 Form에서 자신에게 데이터 전송
HTML form을 사용하여 같은 페이지로 데이터를 전송하는 예제입니다.
<form action="" method="get">
<input type="text" name="username" value="helloget" />
<input type="password" name="password" value="worldget" />
<input type="submit" value="Login" />
</form><form action="" method="get">
<input type="text" name="username" value="helloget" />
<input type="password" name="password" value="worldget" />
<input type="submit" value="Login" />
</form>4.3.3 서버에서 데이터 수신
클라이언트에서 서버로 데이터를 전송하고 서버에서 수신하는 예제입니다.
HTML 클라이언트 코드
<form action="http://127.0.0.1:8000" method="get">
<input type="text" name="username" value="helloget" />
<input type="password" name="password" value="worldget" />
<input type="submit" value="Login" />
</form><form action="http://127.0.0.1:8000" method="get">
<input type="text" name="username" value="helloget" />
<input type="password" name="password" value="worldget" />
<input type="submit" value="Login" />
</form>Python 서버 코드
from http.server import HTTPServer, BaseHTTPRequestHandler # 간단한 서버를 만들 수 있는 모듈
from urllib.parse import urlparse, parse_qs
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self): # GET 요청 처리
parsed_url = urlparse(self.path) # URL 파싱
query_params = parse_qs(parsed_url.query) # 쿼리 파싱
# username과 password 값을 가져옴. 값이 없는 경우 None이 기본값
username = query_params.get('username', [None])[0]
password = query_params.get('password', [None])[0]
if username and password: # 2개 모두 존재하는 경우
response = f'Username: {username}, Password: {password}'
else: # 그렇지 않은 경우에는 form
response = '''
<form action="" method="get">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
'''
self.send_response(200) # HTTP 상태코드 생성(200은 요청이 성공적으로 처리되었다는 것)
self.send_header('Content-type', 'text/html') # 응답은 HTML로 송신
self.end_headers() # 헤더 정보는 여기까지 마무리
self.wfile.write(response.encode('utf-8')) # 응답 메시지 작성
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print(f'Server running on port {server_address[1]}')
httpd.serve_forever()from http.server import HTTPServer, BaseHTTPRequestHandler # 간단한 서버를 만들 수 있는 모듈
from urllib.parse import urlparse, parse_qs
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self): # GET 요청 처리
parsed_url = urlparse(self.path) # URL 파싱
query_params = parse_qs(parsed_url.query) # 쿼리 파싱
# username과 password 값을 가져옴. 값이 없는 경우 None이 기본값
username = query_params.get('username', [None])[0]
password = query_params.get('password', [None])[0]
if username and password: # 2개 모두 존재하는 경우
response = f'Username: {username}, Password: {password}'
else: # 그렇지 않은 경우에는 form
response = '''
<form action="" method="get">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Login">
</form>
'''
self.send_response(200) # HTTP 상태코드 생성(200은 요청이 성공적으로 처리되었다는 것)
self.send_header('Content-type', 'text/html') # 응답은 HTML로 송신
self.end_headers() # 헤더 정보는 여기까지 마무리
self.wfile.write(response.encode('utf-8')) # 응답 메시지 작성
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print(f'Server running on port {server_address[1]}')
httpd.serve_forever()4.3.4 JavaScript의 URL 처리
JavaScript에서 URL을 파싱하고 요청을 보내는 방법을 알아보겠습니다.
URL 파싱
const url = new URL(
'https://www.example.com/path/to/page?key1=value1&key2=value2#section',
);
console.log(url.protocol); // "https:"
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/path/to/page"
console.log(url.search); // "?key1=value1&key2=value2"
console.log(url.hash); // "#section"const url = new URL(
'https://www.example.com/path/to/page?key1=value1&key2=value2#section',
);
console.log(url.protocol); // "https:"
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/path/to/page"
console.log(url.search); // "?key1=value1&key2=value2"
console.log(url.hash); // "#section"요청 보내기
const url = 'https://eduapi.weniv.co.kr/723/product';
fetch(`${url}`)
.then((response) => {
console.log(response.status);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});const url = 'https://eduapi.weniv.co.kr/723/product';
fetch(`${url}`)
.then((response) => {
console.log(response.status);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});쿼리 파라미터와 함께 요청 보내기
const url = 'https://eduapi.weniv.co.kr/753/product/search';
const params = new URLSearchParams({ keyword: 'keyring' });
fetch(`${url}?${params}`)
.then((response) => {
console.log(response.status);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});const url = 'https://eduapi.weniv.co.kr/753/product/search';
const params = new URLSearchParams({ keyword: 'keyring' });
fetch(`${url}?${params}`)
.then((response) => {
console.log(response.status);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});4.3.5 Python의 URL 처리
Python에서 URL을 파싱하고 요청을 보내는 방법을 알아보겠습니다.
URL 파싱
from urllib.parse import urlparse
url = 'https://www.example.com/path/to/page?key1=value1&key2=value2#section'
parsed_url = urlparse(url)
print(parsed_url.scheme) # "https"
print(parsed_url.netloc) # "www.example.com"
print(parsed_url.path) # "/path/to/page"
print(parsed_url.query) # "key1=value1&key2=value2"
print(parsed_url.fragment) # "section"from urllib.parse import urlparse
url = 'https://www.example.com/path/to/page?key1=value1&key2=value2#section'
parsed_url = urlparse(url)
print(parsed_url.scheme) # "https"
print(parsed_url.netloc) # "www.example.com"
print(parsed_url.path) # "/path/to/page"
print(parsed_url.query) # "key1=value1&key2=value2"
print(parsed_url.fragment) # "section"요청 보내기
Colab에서 실습할 경우 설치 없이 해도 되고, 터미널에서 실행할 경우 pip install requests로 모듈을 설치해야 합니다.
import requests
url = 'https://eduapi.weniv.co.kr/523/product/search'
params = {'keyword': 'keyring'}
response = requests.get(url, params=params)
print(response.status_code)
print(response.text)import requests
url = 'https://eduapi.weniv.co.kr/523/product/search'
params = {'keyword': 'keyring'}
response = requests.get(url, params=params)
print(response.status_code)
print(response.text)4.3.6 Python의 URL 인코딩
URL 인코딩(URL Encoding)은 URL에서 특정 문자를 퍼센트 인코딩(Percent Encoding)으로 대체하는 과정을 말합니다. URL에는 ASCII 문자 중 예약 문자나 불안전한 문자가 포함될 수 있는데, 이러한 문자들은 URL에서 특별한 의미를 가지거나 올바르게 전송되지 않을 수 있습니다. 따라서 URL 인코딩을 통해 이러한 문자들을 안전하게 표현할 수 있도록 변환합니다.
인코딩 규칙
| 유지되는 문자 | 인코딩되는 문자 |
|---|---|
| 알파벳(A-Z, a-z), 숫자(0-9) | 공백, 특수문자 등 |
| 하이픈(-), 밑줄(_), 마침표(.), 물결표(~) | 한글 등 비ASCII 문자 |
그 외의 문자들은 퍼센트 기호(%)와 해당 문자의 ASCII 코드에 해당하는 16진수 값으로 대체됩니다.
from urllib.parse import quote, unquote
# URL 인코딩 예제
url = "https://www.example.com/search?q=Hello World!&category=문서"
encoded_url = quote(url)
print("Original URL:", url)
print("Encoded URL:", encoded_url)
# URL 디코딩 예제
decoded_url = unquote(encoded_url)
print("Decoded URL:", decoded_url)from urllib.parse import quote, unquote
# URL 인코딩 예제
url = "https://www.example.com/search?q=Hello World!&category=문서"
encoded_url = quote(url)
print("Original URL:", url)
print("Encoded URL:", encoded_url)
# URL 디코딩 예제
decoded_url = unquote(encoded_url)
print("Decoded URL:", decoded_url)