24.01.24 수
24년 1월 24일... 이사하기 좋은 날인가?
열심히 안 들었던 강의 다시 복습하기!
TIL day는 순서에 맞게 맞춰주고 싶당 ㅎㅎ
Beautifulsoup
BeautifulSoup이란, HTML Parser.
BeautifulSoup 라이브러리 설치
%pip install bs4
BeautifulSoup 객체 만들기
# 모듈 불러오기
import requests
# www.example.com 사이트를 요청한 후 응답 받아보기
res = requests.get("https://www.example.com")
res.text
# BeautifulSoup4 - bs4를 불러와봅시다.
from bs4 import BeautifulSoup
# BeautifulSoup객체를 만들어봅시다.
# 첫번째 인자로는 response의 body를 텍스트로 전달합니다.
# 두번째 인자로는 "html"로 분석한다는 것을 명시해줍니다.
soup = BeautifulSoup(res.text, "html.parser")
# 객체 soup의 .prettify()를 활용하면 분석된 HTML을 보기 편하게 반환해줍니다.
print(soup.prettify())
# title 가져오기
soup.title
# head 가져오기
soup.head
# body 가져오기
soup.body
# <h1> 태그로 감싸진 요소 하나 찾기
h1 = soup.find("h1")
# <p> 태그로 감싸진 요소들 찾기
soup.find_all("p")
# 태그 이름 가져오기
h1.name
# 태그 내용 가져오기
h1.text
예제
# 스크래핑에 필요한 라이브러리를 불러와봅시다.
import requests
from bs4 import BeautifulSoup
# 예시 사이트에 요청을 진행하고, 응답을 바탕으로 BeautifulSoup 객체를 만들어봅시다.
res = requests.get("https://books.toscrape.com/catalogue/category/books/travel_2/index.html")
soup = BeautifulSoup(res.text, "html.parser")
# <h3> 태그에 해당하는 요소를 하나 찾아봅시다.
book = soup.find("h3")
# <h3> 태그에 해당하는 요소를 모두 찾아봅시다.
h3_results = soup.find_all("h3")
h3_results[0]
# book_list에서 우리가 원하는 제목(title)만 추출해봅시다.
for book in h3_results:
print(book.a["title"])
HTML의 Locator인 id와 class를 이용해서 원하는 요소 찾기 - 예제
# 다음 User-Agent를 추가해봅시다.
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)
# 응답을 바탕으로 BeautifulSoup 객체를 생성해봅시다
soup = BeautifulSoup(res.text, "html.parser")
# 질문의 제목을 모아서 가져와봅시다.
questions = soup.find_all("li", "question-list-item")
for question in questions:
print(question.find("div", "question").find("div", "top").h4.text)
## Pagination : 많은 정보를 인덱스로 구분하는 기법
# Pagination이 되어있는 질문 리스트의 제목을 모두 가져와봅시다.
# 과도한 요청을 방지하기 위해 0.5초마다 요청을 보내봅시다.
import time
for i in range(1, 6):
res = requests.get("https://hashcode.co.kr/?page={}".format(i), user_agent)
soup = BeautifulSoup(res.text, "html.parser")
questions = soup.find_all("li", "question-list-item")
for question in questions:
print(question.find("div", "question").find("div", "top").h4.text)
# 중요!!!
time.sleep(0.5)
'[프로그래머스] 데이터엔지니어링 데브코스 1기 > TIL (Today I Learned)' 카테고리의 다른 글
TIL_day10 Seaborn, Wordcloud (0) | 2024.01.25 |
---|---|
TIL_day9 Selenium (1) | 2024.01.24 |
셀레니움 크롬드라이버 설치(버전 이슈) (1) | 2024.01.21 |
TIL_day48 Docker Volume (0) | 2023.06.15 |
TIL_day47 CI/CD, Docker와 Github Actions (1) | 2023.06.13 |