import requests
from bs4 import BeautifulSoup
res = requests.get("https://www.example.com")
res
>> <Response [200]>
soup = BeautifulSoup(res.text, "html.parser")
soup.title
soup.head
soup.body
# 가장 첫 번째 나오는 "h1"태그 찾기
soup.find("h1")
>> <h1>Example Domain</h1>
# 모든 "h1" 태그를 리스트 형태로 뽑아내기
soup.find_all("h1")
# 태그 이름 가져오기
soup.find("h1").name
>> 'h1'
# 태그 내용가져오기
soup.find("h1").text
>> 'Example Domain'
# class가 "page-header"인 div 태그를 찾기
find_result = soup.find("div","page-header")
# 위 결과에서 text 값을 깔끔하게 가져오기.
find_result.h1.text.strip()
>> 'Example web scraping website'
스크랩할 사이트 : https://hashcode.co.kr/
아래 두 가지 원칙을 지킨다.
# 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")