첫번째 실습에선 beautifulsoup 기초 사용법을 배웠다.
%pip install beautifulsoup4
%pip install requests
import requests
res = requests.get("http://www.example.com")
from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text, "html.parser") # html로 parsing한다
print(soup.prettify()) # 보기 편하게
soup.title # title 기져오기
soup.head # head 가져오기
soup.body # body 가져오기
h1 = soup.find("h1") # 요소 찾기
soup.find_all("p") # 해당 요소 모두 찾기
h1.name # 태그 이름 가져오기
h1.text # 태그 내용 가져오기
여기에 있는 책 목록을 사용하여 실습을 진행했다.
이렇게 리스트에 h3 태그 목록들이 담겨있을 때, title을 온전하게 가져오고 싶다면
for book in h3_results:
print(book.a['title'])
이렇게 dict를 활용한다.
수많은 div 중에서도 예를들어 id가 'messages'인 걸 찾고 싶다면,
soup.find("div", id = "messages")
이렇게 하면 결과가
<div id="messages">
</div>
원하는 id를 가진 div만 찾아준다.
반면 특정 class 가진 div들을 찾고 싶다면
soup.find("div", "image_container")
이런식으로 하면 된다.
<div class="image_container">
<a href="../../../its-only-the-himalayas_981/index.html"><img alt="It's Only the Himalayas" class="thumbnail" src="../../../../media/cache/27/a5/27a53d0bb95bdd88288eaf66c9230d7e.jpg"/></a>
</div>
결과는 이렇게!
Pagination 되어있을 경우의 웹 스크랩핑 → page별로 달라지는 홈페이지 주소 활용해서 시간 차로 scrape (time.sleep(0.5)
이런 식으로!)
동적 웹페이지 scrape를 위해서는 from selenium import webdriver
를 이용!