지구정복

[Python] 3/16 | requests(설치, status_code, 특정url의 html출력, get과 post방식), BeautifulSoop(설치, find, find_all, 뉴스기사 크롤링) 본문

데이터 엔지니어링 정복/Python

[Python] 3/16 | requests(설치, status_code, 특정url의 html출력, get과 post방식), BeautifulSoop(설치, find, find_all, 뉴스기사 크롤링)

eeaarrtthh 2021. 3. 16. 11:38
728x90
반응형
SMALL

1. requests 사용

더보기

cmd에서 아래와 같이 경로를 변경한 뒤 pip install 시킨다.

 

페이지 상태값 출력하기

200이 나오면 성공이고 404가 나오면 페이지가 없다는 것이다.

import requests

url = 'https://www.daum.net'
rep = requests.get(url)

#페이지 요청값이 출력
print( rep )





<Response [200]>

 

특정 url의 html 텍스트 가져오기

이때 자동적으로 디코딩이 돼서 가져온다.

import requests

url = 'https://www.daum.net'
rep = requests.get(url)

#페이지 요청값이 출력
print( rep.status_code )

#페이지 html출력
print( rep.text )

#헤더값만 출력
print( rep.headers )

 

get과 post방식 사용하기

import requests

get_url = 'https://httpbin.org/get'
post_url = 'https://httpbin.org/post'

#get방식
get_res = requests.get( get_url)
post_res = requests.post( post_url )

print( get_res.text )
print( post_res.text )






{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.25.1", 
    "X-Amzn-Trace-Id": "Root=1-605017e0-1fbcd5f03a4772ea12f84d6f"
  }, 
  "origin": "220.117.144.98", 
  "url": "https://httpbin.org/get"
}

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "0", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.25.1", 
    "X-Amzn-Trace-Id": "Root=1-605017e1-65b6b2bd0d26cfe54b1d6bbf"
  }, 
  "json": null, 
  "origin": "220.117.144.98", 
  "url": "https://httpbin.org/post"
}


2. bs4BeautifulSoop(bs4) 사용

더보기

먼저 cmd에서 beautifulsoop을 설치해야 한다.
설치 경로를 아래와 같이 바꿔준다.

아래 명령어를 실행한다.

 

이제이클립스 pedev에서 아래와 같이 코딩한다.

import bs4
from bs4 import BeautifulSoup

html_doc = """
 <html>
  <head>
   <title>
    Page title
   </title>
  </head>
  <body>
   <p id="firstpara" align="center">
    This is paragraph
    <b>
     one
    </b>
    .
   </p>
   <p id="secondpara" align="blah">
    This is paragraph
    <b>
     two
    </b>
    .
   </p>
  </body>
 </html>
"""

soup = BeautifulSoup( html_doc, 'html.parser' )
#print( soup.prettify() );
print( soup.title ) #타이틀만 출력
print( soup.title.name )    #타이틀의 벨류값
print( soup.title.string )  
print( soup.title.parent )  #타이틀태그를 감싸고 있는 부모태크








<title>
    Page title
   </title>
title

    Page title
   
<head>
<title>
    Page title
   </title>
</head>

 

이번엔 class가 있는 p태그를 출력해보자. 이때 가장 먼저나오는 것을 가져온다.

import bs4
from bs4 import BeautifulSoup

html_doc = """
 <html>
  <head>
   <title>
    Page title
   </title>
  </head>
  <body>
   <p id="firstpara" align="center" class="stroy">
    This is story
    <b>
     one
    </b>
    .
   </p>
   <p id="secondpara" align="blah" class="title">
    This is title
    <b>
     two
    </b>
    .
   </p>
  </body>
 </html>
"""

soup = BeautifulSoup( html_doc, 'html.parser' )

print( soup.p['class'] )

 

find_all() 사용
이번에는 모든 p태그를 찾아보자
이때 list_p 는 리스트 타입으로 저장된다.

import bs4
from bs4 import BeautifulSoup

html_doc = """
 <html>
  <head>
   <title>
    Page title
   </title>
  </head>
  <body>
   <p id="firstpara" align="center" class="stroy">
    This is story
    <b>
     one
    </b>
    .
   </p>
   <p id="secondpara" align="blah" class="title">
    This is title
    <b>
     two
    </b>
    .
   </p>
  </body>
 </html>
"""

soup = BeautifulSoup( html_doc, 'html.parser' )

list_p = soup.find_all( 'p' )
print( list_p )
print( type( list_p ) )     #리스트타입으로 저장된다.
print( list_p[0] )
print( list_p[1] )





[<p align="center" class="stroy" id="firstpara">
    This is story
    <b>
     one
    </b>
    .
   </p>, <p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>]
<class 'bs4.element.ResultSet'>
<p align="center" class="stroy" id="firstpara">
    This is story
    <b>
     one
    </b>
    .
   </p>
<p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>

 

클래스나 id값을 통해서 가져오기

이때 클래스는 class_ = '클래스명' 을 사용한다.

import bs4
from bs4 import BeautifulSoup

html_doc = """
 <html>
  <head>
   <title>
    Page title
   </title>
  </head>
  <body>
   <p id="firstpara" align="center" class="stroy">
    This is story
    <b>
     one
    </b>
    .
   </p>
   <p id="secondpara" align="blah" class="title">
    This is title
    <b>
     two
    </b>
    .
   </p>
  </body>
 </html>
"""

soup = BeautifulSoup( html_doc, 'html.parser' )

#ID 값으로 검색
print( soup.find_all( id='secondpara' ))

#class로 검색 1
print( soup.find_all( 'p', { 'class': 'title'} ) )

#class로 검색 2
print( soup.find_all( class_='title' ) )









[<p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>]
[<p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>]
[<p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>]

 

보통 find와 find_all을 주로 많이 사용한다.

찾는 태그를 제한하기
limit=제한횟수 를 이용한다.

import bs4
from bs4 import BeautifulSoup

html_doc = """
 <html>
  <head>
   <title>
    Page title
   </title>
  </head>
  <body>
   <p id="firstpara" align="center" class="stroy">
    This is story
    <b>
     one
    </b>
    .
   </p>
   <p id="secondpara" align="blah" class="title">
    This is title
    <b>
     two
    </b>
    .
   </p>
      <p id="secondpara" align="blah" class="content">
    This is content
    <b>
     two
    </b>
    .
   </p>
  </body>
 </html>
"""

soup = BeautifulSoup( html_doc, 'html.parser' )

#p 태그 2개까지만 찾기
print( soup.find_all( 'p', limit=2 ) )





[<p align="center" class="stroy" id="firstpara">
    This is story
    <b>
     one
    </b>
    .
   </p>, <p align="blah" class="title" id="secondpara">
    This is title
    <b>
     two
    </b>
    .
   </p>]

 

실습) 다음 페이지의 뉴스 제목 크롤링하기

 

import bs4
import requests
from bs4 import BeautifulSoup

html_url = 'https://daum.net/'

html_doc = requests.get( html_url ).text

soup = BeautifulSoup( html_doc, 'html.parser' )

titles = soup.find_all( class_='tit_item' )

for title in titles:
    print( title.text )





'국회는 공직자 목에 방울을 메달라!' [TF사...
중대본 "수도권 통제해야 3차 유행 재확산 억제...
산수유·홍매화 만개한 대전 한밭수목원[픽! 대전...
성탄 이브에 세상에 왔다 성탄에 떠난 화가
"우리 엄마 코로나 백신 맞으러"..노모 안고...
역주행 화물차, 핸들 돌려 인명피해 막았다[영상...
귀여움 주의! 쏘대장 운동시켰다가
내 남자의 차에서 발견한 수상한 흔적
카메라 울렁증 있는 자신의 모습에...
연 매출 170억이었던 이곳 현재 상황
찐 권력의 상징 = 초고층 빌딩?! 부자가 초고층에...
(정동원 or 임영웅) 일편단심 서원이의 사랑 고민...
(FULL) 쏘대장님과 함께하는 철원 라이프.. 힐...
일 안 하는 알코올 의존증 아빠 때문에 꿈을 포기했...
서하준, 홍수아 스캔들로 도발하는 진미령에 '착잡'
"철저히 짓밟을 거야" 홍석, 서하준에 복수 선전포...
이다희 - Your Eyes(Acoustic ver...
'스카이캐슬, 완벽한 타인' 레전드 작품에 이어 예...
뜻밖의 애국 포마드
곱빼기 시켰는데 양이 너무 많아서.jpg
'먹방 열풍'? 이곳, 전혀 다른 세상
따뜻한 날씨가 반갑지 않은 건...
독을 마시면서까지 시도했던 것
당신에게 '녹색'을 처방합니다
"휴지만 사도 손이 벌벌 떨려요..."
그럼에도, 전화주문은 있어야 합니다
하루 평균 7개나 필요하다는데...
이 청년들이 주말을 반납하고 하는 일

 

728x90
반응형
LIST
Comments