BeautifulSoup

geunyeongii·2022년 10월 9일
0
post-thumbnail

객체 만들기

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를 이용해서 값 가져오기

# 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")
profile
✏️세상의 모든 기록 ✏️

0개의 댓글