1. DOM (Document Object Model)

  • 브라우저의 렌더링 엔진은 웹 문서를 로드한 후, 파싱을 진행
  • 파싱 스크린샷 2023-10-25 오후 1 04 07

  • 파싱으로 만들어진 모델을 DOM이라고 함!

스크린샷 2023-10-25 오후 1 20 59

브라우저가 HTML을 DOM으로 바꾸어 사용하는 이유

  • 각 노드를 객체로 생각하면 문서를 더욱 편리하게 관리할 수 있음
    • 객체의 일과 성질을 활용할 수 있음
    • body.din 등으로 접근할 수 있음
      • 계층 구조
  • HTML 문서를 한 번에 쓰지 않아도, 나중에 python, JS 등 언어와 같이 조작할 수 있음

1) DOM Tree를 순회해서 특정 원소를 추가할 수 있음 (삭제 및 변경도 가능)

  • ex)
    var imgElement = document.createElement("img");
    document.body.appendChild(imgElement);
    

2) DOM Tree를 순회해서 특정 원소를 찾을 수 있음

  • ex)
    document.getElementByTagName("h2");
    

브라우저의 렌더링 요약

  • 스크래핑 관점에서
  • 브라우저는 HTML을 파싱해서 DOM 생성
  • 이를 바탕으로 요소를 변경하거나 찾을 수 있음
  • 파이썬으로 HTML을 분석하는 HTML Parser가 필요!

2. BeutifulSoup

  • 웹 페이지에서 원하는 요소만 가져올 수 있도록 HTML 코드를 분석해주는 HTML Parser 중 하나
import requests
from bs4 import BeautifulSoup

res = requests.get("https://www.example.com")

# BeautifulSoup 객체 생성
soup = BeautifulSoup(res.text, "html.parser")

# 분석된 HTML 보기 편하게 반환
print(soup.prettify())

# title 가져오기
soup.title

# head 가져오기
soup.head

# <h1> 태그로 감싸진 요소 하나 찾기
soup.find("h1")

# <p> 태그로 감싸진 요소들 찾기
soup.find_all("p")

# 태그 내용 가져오기
h1 = soup.find("h1")
h1.text

3. h3 스크래핑

http://books.toscrape.com/catalogue/category/books/travel_2/index.html

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> 태그에 해당하는 요소 모두 찾기
h3_result = soup.find_all("h3")

print(len(h3_result))
print(h3_result[0])
## 11
## <h3><a href="../../../its-only-the-himalayas_981/index.html" title="It's Only the Himalayas">It's Only the Himalayas</a></h3>

# book_list에서 제목만 추출하기
h3_result[0].a.text
## "It's Only the Himalayas"

# 리스트에 넣기
ls = []

for book in h3_result:
    ls.append(book.a["title"])

4. Locator로 원하는 요소 찾기

  • 태그의 속성
    • tagname : 태그의 이름
    • id : 하나의 고유 태그를 가리키는 라벨
    • class : 여러 태그를 묶는 라벨
<p>This element has only tagname</p>
<p id="target">This element has tagname and id</p>
<p class="targets">This element has tagname and class</p>


import requests
from bs4 import BeautifulSoup

res = requests.get("http://example.python-scraping.com/")

soup = BeautifulSoup(res.text, "html.parser")
  • id를 이용해서 요소 가져오기
    • 요소 하나를 지칭하는 특별한 별명 (겹칠 수 없음!)
    • 해당하는 태그 단 하나를 쉽게 가져올 수 있음
soup.find("div", id="results")
  • class를 이용해서 요소 가져오기
    • 유사한 요소들을 구분짓는 별명
    • 해당하는 태그 단 하나를 쉽게 가져올 수 있음
    • ex) 차트 속의 데이터 등
find_result = soup.find("div", "page-header")

# 결과값 공백 삭제하고 출력 : .strip()
find_result.h1.text.strip()

5. 하위 계층 태그 가져오기 & 페이지네이션

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)

soup = BeautifulSoup(res.text, "html.parser")

# 질문의 제목 모아서 가져오기
questions = soup.find_all("li", "question-list-item")   # li 태그, class는 question-list-item

for question in questions:
    print(question.find("div", "question").find("div", "top").h4.text)

What is outstaffing?
flask를 vscode에서 gunicorn을 활성화해서 실행시키고 싶은데 gunicorn을 활성화했는데도 wsgi 서버를 활용하지 않느다고 오류메세지가 뜨네요
MSSQL 2008->2019 마이그레이션 후 게시판 정렬 문제
묵시적 형변환
y값이 입력이 안됩니다.
이 방식으로 배포하는 게 맞나요?
스택 자료 삭제 알고리즘 문제 관련 궁금한 점
프로그램에 대하여
iframe의 토큰 관련 질문입니다!
css border 속성 관련 질문 드립니다.
vscode 관련 질문 드립니다.
Flutter를 노마드코더를 통해 공부하려는데 세팅에서 막혔어요
프로그래머스 입문
파이썬 기본 문제

페이지네이션

  • 많은 정보를 인덱스로 구분하는 기법
  • Query String
    • https://hashcode.co.kr/?page={i}
import time

for i in range(1, 6):
    print("-----[" + str(i) + "]-----")
    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(1)
  • 1초 간격으로 요청을 보내서 정보 받아옴