yon11b

[SK 쉴더스 루키즈] 파이썬 데이터 통계1 (크롤링, RDBMS) 본문

보안/SK 쉴더스 루키즈

[SK 쉴더스 루키즈] 파이썬 데이터 통계1 (크롤링, RDBMS)

yon11b 2026. 3. 14. 21:43
반응형

ML: 데이터 수집 → 데이터 정제 → 학습 → 검증

 

BeutifulSoup

from bs4 import BeautifulSoup
html_doc = """
<html>
    <head>
        <title>Example Page</title>
    </head>
    <body>
        <h1 class="description">Welcome to Web Scraping</h1>
        <p class="description title big">This is an example paragraph.</p>
        <a href="https://example.com1">Visit Example1</a>
        <a href="https://example.com2">Visit Example2</a>
        <a href="https://example.com3">Visit Example3</a>
        <a href="https://example.com4">Visit Example4</a>
    </body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser') # html 로 추출할 거야.
a_tags = soup.find_all('a')

links=[]
for a_tag in a_tags:
    print(a_tag['href'])    # https://example.com1
                            # https://example.com2
                            # https://example.com3
                            # https://example.com4
    links.append(a_tag['href'])
print(links)

 

css 선택자

# class = 'description title big small'
tag = soup.select('.description')

 

 

태그말고 txt만 뽑아내기: item.get_text()

import requests
url_2 = 'https://news.ycombinator.com/'
response = requests.get(url_2)
soup2 = BeautifulSoup(response.text, 'html.parser')

for item in soup2.find_all('a'):
    href_text=  item.get('href')
    title_text = item.get_text()
    if href_text:
        print(title_text, href_text)
코드 결과값 (출력 내용) 설명
print(item) <a href="...">파이썬 크롤링 기초...</a> 태그 전체(HTML 소스)를 가져옴
print(item.get_text()) 파이썬 크롤링 기초 수업 태그를 떼어내고 "알맹이 텍스트"만 가져옴

 

SQLite

- 서버 설치가 필요 x. python 내장 모듈로 쉽게 사용할 수 있음
- RDBMS
    - 테이블 형식으로 데이터 관리
    - 저장할 공간 생성 → 테이블을 생성

sql_create = '''
create table user (
    id integer primary key autoincrement,
    name text not null,
    age intger,
    city text
)
'''
conn = sqlite3.connect('first.db')
print('DB 연결 성공')
cursor = conn.cursor()
cursor.execute(sql_create)

conn.close()

cursor = conn.cursor() 는 데이터베이스를 조작하기 위한 커서 객체를 만드는 코드

DB는 직접 SQL을 실행하지 않는다. 그래서 cursor가 SQL을 전달하는 역할을 한다.

 

변경사항이 있으면 commit을 해주어야 한다.

 

1️⃣ 같은 연결(conn) 안에서는 변경 내용이 보인다

코드 흐름

cursor.execute(sql_insert, ...)
cursor.execute('select * from user')

여기서 INSERT 후 commit 안 했어도 같은 connection 내부에서는 변경 내용이 보인다.

INSERT (아직commit 안됨)
↓SELECT (같은connection)
↓
데이터 보임

그래서 출력은 된다.

 

2️⃣ 하지만 DB 파일에는 아직 저장 안 됐을 수도 있다

commit() 안 하면 트랜잭션 상태에 있는 것이다.

RAM
↓commit
↓
DB 파일 저장
sql_insert = "INSERT INTO user (name, age, city) VALUES (?, ?, ?)"

conn = sqlite3.connect('first.db')
print('DB 연결 성공')
cursor = conn.cursor()
cursor.execute(sql_insert, ('yon11b', 25, 'seoul'))
cursor.execute('select * from user')
conn.commit()
rows = cursor.fetchall()
for row in rows:
    print (row)
conn.close()

 

 

 

 

 

728x90