import requests
page = requests.get("URL")
page
dcu = page.text
requests.get : 메서드를 사용해 지정된 URL에 HTTP GET 요청
: 데이터를 가져와 page 변수에 저장
:text는 http 응답의 본문 데이터를 가져오지만, 만약 JSON 데이터를 반환하는 API라면 page.json 사용
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find('tbody')
rows = table.find_all('tr')
print(table)
print(rows)
: HTML 구조를 분석 가능한 객체로 변환(파싱)
: <tbody> 태그 내에서 모든 <tr> 태그를 찾아 리스트 반환
for row in rows:
list = row.find_all('td')
번호 = list[0].text.strip()
제목 = list[1].find('a').text.strip()
작성자 = list[3].text.strip()
등록일 = list[4].text.strip()
조회수 = list[5].text.strip()
print(f"번호: {번호}, 제목: {제목}, 작성자: {작성자}, \
등록일: {등록일}, 조회수: {조회수}")
: 특정 순번의 list에서 <td> 태그 텍스트를 가져옴
strip() : 앞뒤 공백 제거
import pandas as pd
numbers = []
titles = []
writers = []
dates = []
views = []
for row in rows:
list = row.find_all('td')
번호 = list[0].text.strip()
제목 = list[1].find('a').text.strip()
작성자 = list[3].text.strip()
등록일 = list[4].text.strip()
조회수 = list[5].text.strip()
numbers.append(번호)
titles.append(제목)
writers.append(작성자)
dates.append(등록일)
views.append(조회수)
df = pd.DataFrame({
"번호": numbers,
"제목": titles,
"작성자": writers,
"등록일": dates,
"조회수": views
})
df
: 데이터프레임 형태로 관리하고 처리함이 목적
: 빈 리스트 생성(nubers, titles ...)
: 데이터를 가져온 후 "append"를 통해 리스트에 저장
: 데이터프레임 생성 및 매핑(구조화)
'Web Study > practice' 카테고리의 다른 글
Python) 네이버 뉴스 기사 크롤링 & HTML 파싱 필요성 (0) | 2024.12.17 |
---|---|
HTML & CSS로 간단한 회원가입 폼 제작 및 CSS 선택자 우선순위 규칙 (0) | 2024.12.12 |
VS Code + 미니콘다: Python 개발 환경 구축하기 (0) | 2024.12.11 |