
- HTML을 분석해주는
BeautifulSoup- 동적 웹사이트
requests모듈을 이용하여 HTTP 요청을 보내고 응답을 받아 여러 요소를 살펴볼 수 있는데 응답의 내용이 아주 긴 텍스트로 오기 때문에 분석하기 어렵다는 문제점이 있다.BeautifulSoup4라이브러리를 이용한다면HTML Parser를 사용해 HTML 코드를 우리가 원하는 요소만 가져올 수 있다.
pip install bs4
import requests
from bs4 import BeautifulSoup
res = requests.get("https://www.example.com")
soup = BeautifulSoup(res.text, "html.parser")
print(soup.prettify())
<!DOCTYPE html>
<html>
<head>
<title>
Example Domain
</title>
<meta charset="utf-8"/>
<meta content="text/html; charset=utf-8" http-equiv="Content-type"/>
<meta content="width=device-width, initial-scale=1" name="viewport"/>
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 2em;
background-color: #fdfdff;
border-radius: 0.5em;
box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
}
...
</div>
</body>
</html>
soup.title # title 태그를 추출
soup.head # head 태그를 추출
soup.find("h1") # <h1> 태그로 감싸진 요소 하나 찾기
soup.find_all("h1") # <h1> 태그로 감싸진 요소들 찾기
soup.find("h1").name # 태그 이름 가져오기
soup.find("h1").text # 태그 내용 가져오기
import requests
from bs4 import BeautifulSoup
res = requests.get("http://books.toscrape.com/catalogue/category/books/travel_2/index.html")
soup = BeautifulSoup(res.text,"html.parser")
h3_results = soup.find_all("h3")
for book in h3_results: #
print(book.a["title"])
id class 로 원하는 요소 찾기import requests
from bs4 import BeautifulSoup
res = requests.get("http://example.python-scraping.com/")
soup = BeautifulSoup(res.text, "html.parser")
soup.find("div", id="results") #id 가 results인 div 태그를 찾기
find_result = soup.find("div", "page-header") # class가 "page-header"인 div 태그를 찾기
find_result.h1.text.strip() # text 값 깔끔하게 가져오기
user_agent = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}
import requests
from bs4 import BeautifulSoup
res = requests.get("https://hashcode.co.kr/", user_agent)
soup = BeautifulSoup(res.text, "html.parser")
# li 태그를 가지고 class 가 question-item-list인 요소들을 추출
questions = soup.find_all("li", "question-list-item")
# 추출한 요소들 중 question 클래스의 div태그 중 top 클래스의 div 태그의 h4 태그의 text를 추출
for question in questions:
print(question.find("div","question").find("div", "top").h4.text)
- 정적(static) 웹 사이트 : HTML 내용이 고정됨. 같은 요청을 받으면 같은 응답을 받음, HTML 문서가 완전하게 응담.
- 동적(dynamic) 웹 사이트 : HTML 내용이 변함. 새로고침을 할 때마다 새로운 웹 페이지를 불러오는 것 같은 예. 응답 후 HTML이 렌더링이 될 때까지의 지연시간이 존재.
동기 처리 : 요청에 따른 응답을 기다린다. HTML 로딩에 문제가 없다.
비동기 처리 : 요청에 따른 응답을 기다리지 않는다. 상황에 따라서 데이터가 완전하지 않은 경우가 발생.
Selenium 라이브러리)