각진 세상에 둥근 춤을 추자

[Python] 크롤링 HTML 페이지 요청하기 본문

Python

[Python] 크롤링 HTML 페이지 요청하기

circle.j 2023. 1. 18. 12:13
1. 모듈 설치

 

pip install requests
pip install bs4

 

설치 후, 본문 맨 윗 부분에 import문 작성

import requests as req
from bs4 import BeautifulSoup as bs

 

 

[ERROR] zsh: command not found: pip 참고 [Error] - [Python] pip install ~ 에러

 

[Python] pip install ~ 에러

pip install ~ 입력 시 에러 (예) pip install onenpyxl, pip install requests, pip install bs4 ... zsh: command not found: pip ModuleNotFoundError: No module named 'pymysql' (1번 방법) pip3 install --upgrade pip (2번 방법) pip3 install (설치 프

this-circle-jeong.tistory.com

 

 


2. HTML 요청

 

url = 'http://chhak.click/parsing/sample2.html'
html = req.get(url).text

 

 


3. 문서 객체 생성 (HTML 파싱)

 

dom = bs(html, 'html.parser')

 

 


4. 데이터 파싱

 

위 주소의 웹 페이지에서 마우스 우클릭 - 검사 - 요소에서 해당 데이터의 셀렉터를 복사한다. 

 

예를 들어, h1 태그로 입력된 '스크래핑이란?'이라는 텍스트의 셀렉터를 복사한다. 

 

select_one

# 방법1: 복사한 셀렉터를 괄호 안에 붙여넣기
tit = dom.select_one('#tit').text

# 방법2: 태그 이용하기
tit = dom.html.body.h1.text

 

 

 

이번에는 리스트의 셀렉터를 복사한다.

 

select

lis = dom.select('ul > li')