본문 바로가기
Python/Web Scrapping

1. requests와 beautifulsoup

by Sondho 2020. 4. 1.

requests : HTTP for Humans

  • python에는 기본적으로 requests와 비슷한 기능을 하는 *urllib라이브러리를 지원하지만 requests모듈이 사용하기 쉽고 간단하게 되어있다고 생각한다.

*urllib : [https://docs.python.org/3/library/urllib.html]

1. 설치 및 import

pip install requests
import requests

 

2. 사용방법

  • get
res = requests.get(" 얻고자 하는 사이트 url ")
# 해당 url의 html정보를 요청한다.

 

  • status_code
res.status_code
# 해당 url에 요청을 했을 때의 상태코드가 반환된다.

200이 리턴될 경우, ok라는 뜻이다.
400번대는 클라이언트 에러, 500번대는 서버측 에러이다.

 

  • content 또는 text

text와 content는 응답 내용(html의 내용)을 보여줌

res.conent
# content는 바이트단위로 출력

res.encoding = 'utf-8'  // text를 사용하기전 .encoding으로 설정 가능
res.text
# text는 텍스트형식으로 바로 유니코드 반환
# UTF-8과 같은 문자 인코딩을 사용하여 문자열로 반환할 수 있다.

※ 참고 : Python Requsets Library https://realpython.com/python-requests/

 

Python’s Requests Library (Guide) – Real Python

In this tutorial on Python's "requests" library, you'll see some of the most useful features that requests has to offer as well as how to customize and optimize those features. You'll learn how to use requests efficiently and stop requests to external serv

realpython.com


BeutifulSoup 모듈

1. 설치 및 import

// 설치
$ pip install beautifulsoup4
// import
from bs4 import BeautifulSoup

 

2. 사용 방법

  • parsing
res_soup = BeautifulSoup(res.text, 'html.parser')

# res에 얻은 정보를 html parsing하겠다.

* 파싱(Parsing) : 어떤 페이지(문서, html 등)에서 내가 원하는 데이터를 특정 패턴이나 순서로 추출하여 정보로 가공하는 것

 

  • find

   - 조건에 맞는 첫번째 태그를 반환.

pagination = res_soup.find("태그명", {"어트리뷰트":"어트리뷰트 값"}).find("태그명")
# parsing된 res_soup에서 find()함수를 이용해 특정 태그와 해당하는 클래스를 찾는다.

태그명 : a, div, script, table, style 등
어트리뷰트(Attributes) : class, id, type, role, title 등
ex)

   div 태그가 값이 ‘my-class’인 class 어트리뷰트를 가지고 있다.

 

  • find_all (recursive,

  - 조건에 맞는 모든 태그를 반환

  - 리스트형으로 반환된다. (중요)

a_all = pagination.find_all("a")
# pagitnation(변수명)안에 있는 태그명 'a' 전체를 찾는다.


# find_all("태그명")["어트리뷰트"]
a_all = pagination.find_all("a").find_all("b")["title"]
# 태그명 a 전체에서 태그명 b 전체의 어트리뷰트 title을 찾는다.
# ex)
results = soup.find_all("div", {"class":"-job"})
for result in results:
      print(result["data-jobid"])
# result의 data-jobid어트리뷰트의 값을 출력한다.

#find_all("태그명", recursive=False)

 

  • get_text() / string

  - get_text()

 

    - 현재 태그를 포함하여 모든 하위 태그를 제거하고 유니코드 텍스트만 들어있는 문자열을 반환

    - 항상 마지막 태그에 사용해야함

 

  - string

   

    - 태그(tag) 내 문자열을 반환

 

    - 태그 내에 하위 태그가 두개 이상일 경우 무엇을 반환해야 하는지 명확하지 않기 때문에 None을 반환

 

    - 태그 내에 하위 태그가 하나이고 그 안에 문자열이 존재할 경우 해당 문자열을 반환

# HTML
<div class="pagination" >
 <b>1</b>
</div>
# python
aaaa.find("div", {"class":"pagination"}).string

# 1출력됨

 

  • select('상위태그 > 하위태그')

  - 태그명으로 접근이 가능하며, list로 반환된다.

a = soup.select('table > tbody > tr')

print(type(a))

# 실행결과

<class 'list'>

 

참고

Beautifulsoup Documentation https://www.crummy.com/software/BeautifulSoup/bs4/doc/

 

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call str() on a BeautifulSoup object (unicode() in Python 2), or on a Tag within it: str(soup) # ' I linked to example.com ' str(soup.a) # ' I linked to example.com ' The str(

www.crummy.com

 

댓글