코드비
코드비의 개발/데이터공부
코드비
전체 방문자
오늘
어제
  • 분류 전체보기 (53)
    • IT 사전 (16)
    • IT 뉴스 (3)
    • 알고리즘 문제풀이 (2)
    • 01. 파이썬 공부 (16)
    • 02. 웹크롤링 (2)
    • 03. SQL (5)
    • 생각기록 (1)

블로그 메뉴

  • 🐍파이썬 기본문법
  • 😺깃헙
  • 🖋
  • 방명록

공지사항

  • 내가 개발 공부를 시작한 이유

인기 글

태그

  • Android
  • 고수준언어
  • 메인보드
  • HDD
  • python3
  • IDE
  • 메모리
  • 전원
  • 운영체제
  • SSD
  • 오라클
  • SQL
  • 저수준언어
  • 데이터베이스툴
  • 백준
  • 버추얼박스
  • c언어
  • Java
  • CPU
  • 맥OS
  • DB툴
  • 윈도우
  • ios
  • 가상컴퓨터
  • VirtualBox
  • 컴퓨터
  • 프로그래밍언어
  • 파이썬
  • 개발자란
  • 저장장치

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
코드비

코드비의 개발/데이터공부

[웹 크롤링] 웹페이지의 html 가져오기 - requests 모듈
02. 웹크롤링

[웹 크롤링] 웹페이지의 html 가져오기 - requests 모듈

2022. 6. 19. 17:35
requests 모듈이란?

파이썬 사용자를 위한 라이브러리로, HTTP/HTTPS 웹 페이지에 요청(get, post, put, delete)하기 위해 사용되는 모듈

 

웹페이지의 html (텍스트로) 가져오기

1. requests 모듈 설치

2. requests 모듈 사용

3. 원하는 웹페이지의 url 입력

4. requests.get() - html 가져오기 요청 

5. print(.text) - html 텍스트로 출력

 

코드
pip install requests

ㄴ다른 코드나 주석 있으면 설치 안됨..

#모듈 사용
import requests

#원하는 http/https 웹페이지 주소 입력 > 반드시 ""로 묶는다!
url = "https://code-be.tistory.com/" #url은 변수임!

#웹페이지에 get 요청해서 html 가져옴
html = requests.get(url) #html은 변수임!

#html을 text 형식으로 출력하기
print(html.text)

결과는 

<!DOCTYPE html> <html id="__hELLO" lang="ko" data-theme="#"> <head> <link rel="stylesheet" type="text/css" href="https://t1.daumcdn.net/tistory_admin/lib/lightbox/css/lightbox.min.css" /><link rel="stylesheet" type="text/css" href="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-9f4d45bd8395dacec3792f4fa9b5a77e4615ae22/blogs/style/content/font.css?_version_=tistory-9f4d45bd8395dacec3792f4fa9b5a77e4615ae22" /><link rel="stylesheet" type="text/css" href="https://t1.daumcdn.net/tistory_admin/assets/blog/tistory-9f4d45bd8395dacec3792f4fa9b5a77e4615ae22/blogs/style/content/content.css?_version_=tistory-9f4d45bd8395dacec3792f4fa9b5a77e4615ae22" /><!--[if lt IE 9]><script src="https://t1.daumcdn.net/tistory_admin/lib/jquery/jquery-1.12.4.min.js"></script><![endif]--><!--[if gte IE 9]> <!--><script src="//t1.daumcdn.net/tistory_admin/lib/jquery/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script><!--<![endif]--> <script src="https://t1.daumcdn.net/tistory_admin/lib/lightbox/js/lightbox-plus-jquery.min.js"></script> <script> lightbox.options.fadeDuration = 200; lightbox.options.resizeDuration = 200; lightbox.options.wrapAround = false; lightbox.options.albumLabel = "%1 / %2"; </script> <script>var tjQuery = jQuery.noConflict(true);</script><style type="text/css">.tt_article_useless_p_margin p {padding-top:0 !important;padding-bottom:0 !important;margin-top:0 !important;margin-bottom:0 !important;}</style><meta name="referrer" content="always"><link rel="icon" href="//t1.daumcdn.net/tistory_admin/static/top/favicon_0630.ico" /><link rel="apple-touch-icon" href="//img1.daumcdn.net/thumb/C180x180/?fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F5351219%2Fattach%2F05e1acd054e04dccb291f3f16f888dba"> <link rel="apple-touch-icon" sizes="76x76" href="//img1.daumcdn.net/thumb/C76x76/?fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F5351219%2Fattach%2F05e1acd054e04dccb291f3f16f888dba"> <link rel="apple-touch-icon" sizes="120x120" href="//img1.daumcdn.net/thumb/C120x120/?fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F5351219%2Fattach%2F05e1acd054e04dccb291f3f16f888dba"> <link rel="apple-touch-icon" sizes="152x152" href="//img1.daumcdn.net/thumb/C152x152/?fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F5351219%2Fattach%2F05e1acd054e04dccb291f3f16f888dba"> <meta name="google-adsense-platform-account" content="ca-host-pub-9691043933427338"> <meta name="google-adsense-platform-domain" content="tistory.com"> <meta name="description" content=""> <!-- BEGIN OPENGRAPH --> <link rel="canonical" href="https://code-be.tistory.com" /><meta property="og:type" content="website" /><meta property="og:url" content="https://code-be.tistory.com" /><meta property="og:site_name" content="코드비의 개발/데이터공부" ><meta property="og:title" content="코드비의 개발/데이터공부" ><meta property="og:description" content="" ><meta property="og:image" content="https://tistory3.daumcdn.net/tistory/5351219/attach/05e1acd054e04dccb291f3f16f888dba" ><meta property="og:article:author" content="코드비" > <!-- END OPENGRAPH -->

...

</div> <div id="tistoryEtcLayer" class="layer_post"></div><div id="tistorySnsLayer" class="layer_post"></div></body> </html>
서버 상태 확인하기 - .status_code 활용!

200이면 요청 성공, 404/403/500은 실패

import requests
url = "https://code-be.tistory.com/" 
html = requests.get(url) 

#서버 상태 확인하기1
status = html.status_code #status는 변수
print(status)

#서버 상태 확인하기2
print(html)

결과는 

200
<Response [200]>

가져온 데이터를 파일로 저장하기(크롤링한 데이터 저장하는 방법!)

구조는 이러하다

'w'는 쓰기 모드라는 뜻

encoding='utf-8'은 한글이 깨지지 않도록 하는 옵션이다

#파일 객체를 연다
f = open("파일명.확장자", 'w', encoding='utf-8') #file은 변수다 

#객체에 requests로 가져온 데이터를 텍스트 형식으로 쓴다
f.write(html.text)

#파일 객체를 닫는다
f.close()

 

그러니까 위에 데이터를 'html 파일'로 저장하고 싶다면

f = open("블로그_첫화면.html", 'w', encoding='utf-8') 
f.write(html.text)
f.close()

결과는

데이터를 'txt 파일'로 저장하고 싶다면

f = open("블로그_첫화면.txt", 'w', encoding='utf-8') 
f.write(html.text)
f.close()

 


https://me2nuk.com/Python-requests-module-example/

 

Python requests 모듈(module) 사용법

Python requests 모듈(module) 사용법

me2nuk.com

 

'02. 웹크롤링' 카테고리의 다른 글

[웹크롤링] 서버 요청 실패 시, 사용자 에이전트(User-Agent) 활용하기  (0) 2022.06.19
    코드비
    코드비

    티스토리툴바