파이썬 requests 모듈은 웹 서버에 요청을 보내고 응답 객체를 받는데 사용한다. 응답 객체 중에서 HTML 소스 코드를 얻는 방법을 알아본다. 

 

import requests

url = "https://www.wikipedia.org/"
resp = requests.get(url)

html = resp.text
print(html[:1000])

1. requests 모듈을 불러온다.

 

2. 위키피디아 웹 주소를 변수에 저장한다. 

 

3. 웹 서버에 GET 요청을 보내고, 서버가 응답한 객체를 변수에 저장한다.

 

4. text 속성에 HTML 소스코드가 들어 있다. 

 

5. 문자열로 저장되어 있는 HTML 소스코드를 출력한다. 앞에서 1000개의 글자를 지정하여 일부 소스코드만 확인한다. 


<실행 결과 > HTML 소스코드 확인

<!DOCTYPE html>
<html lang="mul" class="no-js">
<head>
<meta charset="utf-8">
<title>Wikipedia</title>
<meta name="description" content="Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation.">
<![if gt IE 7]>
<script>
document.documentElement.className = document.documentElement.className.replace( /(^|\s)no-js(\s|$)/, "$1js-enabled$2" );
</script>
<![endif]>
<!--[if lt IE 7]><meta http-equiv="imagetoolbar" content="no"><![endif]-->
<meta name="viewport" content="initial-scale=1,user-scalable=yes">
<link rel="apple-touch-icon" href="/static/apple-touch/wikipedia.png">
<link rel="shortcut icon" href="/static/favicon/wikipedia.ico">
<link rel="license" href="//creativecommons.org/licenses/by-sa/3.0/">
<style>
.sprite{background-image:url(portal/wikipedia.org/assets/img/sprite-3f2e1b8f.png);background-image:linear-gradient(transparent,transparent),url(portal/wikipedia.org/assets/img/sprite-3f2e1b8f.svg);background

 

+ Recent posts