파이썬 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
'파이썬 데이터 분석 > 웹 스크래핑' 카테고리의 다른 글
[6] 파이썬 웹 스크래핑 - BeautifulSoup 클래스 객체 (0) | 2019.08.05 |
---|---|
[6] 파이썬 웹 스크래핑 - 로봇 배제 표준(robots.txt) (0) | 2019.08.02 |
[4] 상장사 재무제표 수집 (pandas) (0) | 2018.08.16 |
[3] 네이버 주식 시세 (주가 정보) 스크래핑(scraping) 예제 (0) | 2018.07.02 |
[2] KOSPI 주식 종목 리스트 가져오기 -pandas.read_csv (5) | 2018.06.27 |