Notice
Recent Posts
Recent Comments
Link
jyamethyst21 님의 블로그
머신러닝 & 딥러닝 본문
데이터 수집
1) requests 모듈
- http 요청을 보내고 응답을 처리하는 데 사용되는 라이브러리
- 웹 서버와 통신하여 데이터를 가져오거나 전송하는 작업을 쉽게 수행
import requests
url = 'url명'
response = requests.get(url)
if response.status_code == 200:
# 상태 코드 200은 성공을 의미
print("데이터 가져오기 성공!")
print(response.text[:500])
# 응답 본문의 일부 출력
else:
print(f"오류 발생: {response.status_code}")
import requests
url = 'url명'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# JSON 응답을 딕셔너리로 변환
print(f"제목: {data['title']}")
print(f"내용: {data['body']}")
else:
print(f"오류 발생: {response.status_code}")
- response.txt : 응답 본문을 문자열로 반환
- response.json() : json 형식의 응답을 딕셔너리로 반환
- response.status_code: http 상태 코드 반환
import requests
url = 'url명'
params = {'userId': 1} # userId가 1인 게시글 가져오기
response = requests.get(url, params=params)
if response.status_code == 200:
print("사용자 게시글 가져오기 성공!")
print(response.json())
else:
print(f"오류 발생: {response.status_code}")
BeautifulSoup
1) BeautifulSoup
- 파이썬에서 html, xml 문서를 파싱하고 원하는 데이터를 쉽게 추출할 때 사용하는 라이브러리
from bs4 import BeautifulSoup
html_doc = """
<html>
<head><title>Example Page</title></head>
<body>
<h1>Welcome to Web Scraping</h1>
<p class="description">This is an example paragraph.</p>
<a href="https://example.com">Visit Example</a>
</body>
</html>
"""
# BeautifulSoup 객체 생성
soup = BeautifulSoup(html_doc, 'html.parser')
# 태그 탐색
print(soup.title.string)
print(soup.h1.string)
print(soup.a['href'])
# 결과
Example Page
Welcome to Web Scraping
https://example.com
2) find_all(), find()
html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1>Welcome to Web Scraping</h1>
<p class="description title">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')
# find(tag): 특정 태그에 해당하는 값 한개만 출력, find_all(tag) : 전부 출력
a_tag = soup.find('a')
print(a_tag)
# 결과:
<a href="https://example.com1">Visit Example1</a>
a_tags = soup.find_all('a')
links = []
for a_tag in a_tags:
print(a_tag['href'])
links.append(a_tag['href'])
print(links)
# 결과:
https://example.com1
https://example.com2
https://example.com3
https://example.com4
['https://example.com1', 'https://example.com2', 'https://example.com3', 'https://example.com4']
SQLite
1) SQLite
- 가볍고 파일 기반의 관계형 데이터베이스 관리 시스템
- 서버 설치가 필요 없으며, 파이썬 내장 모듈로 쉽게 사용할 수 있음
# 기본 문법
import sqlite3
conn = sqlite3.connect('first.db') # 파일이름 넣기, 없으면 새로 생성
conn.close()
# 1. 테이블 생성
sql_create = '''
create table user (
id integer primary key autoincrement,
name text not null,
age integer,
city text
)
conn = sqlite3.connect('first.db')
cursor = conn.cursor() # 여러 기능 사용해주는 객체
# sql 실행
cursor.execute(sql_create)
print('table 생성')
conn.close()
# 2. 데이터 삽입
sql_insert = '''
insert into user (name, age, city) values (?, ?, ?)
'''
conn = sqlite3.connect('first.db')
cursor = conn.cursor()
# cursor.execute(sql_insert, ('cool', 20, 'Seoul')
data = [
('cool', 20, 'Seoul'),
('cool', 30, 'Seoul'),
('cool', 40, 'Seoul')
]
cursor.executemany(sql_insert, data)
conn.commit()
conn.close()
# 3. 데이터 조회
sql_select = '''
select * from user
'''
conn = sqlite3.connect('first.db')
cursor = conn.cursor()
cursor.execute(sql_select)
rows = cursor.fetchall() # fetchall(): 모든 조회 결과를 가져옴, fetchone(): 한 행씩 가져옴
print(rows)
for row in rows:
print(row)
for id, name, age, city in rows:
print(id, name, age, city)
conn.close()
# 4. 데이터 수정
sql_update = '''
update user set age = ? where id = ?
'''
conn = sqlite3.connect('first.db')
cursor = conn.cursor()
cursor.execute(sql_update, (25, 4) )
conn.commit()
conn.close()
# 5. 데이터 삭제
sql_delete = '''
delete from user where id = ?
'''
conn = sqlite3.connect('first.db')
cursor = conn.cursor()
cursor.execute(sql_delete, (4,) )
conn.commit()
conn.close()'보안 & IT 지식 🌺' 카테고리의 다른 글
| 머신러닝 & 딥러닝 (0) | 2026.01.09 |
|---|---|
| 머신러닝 & 딥러닝 (0) | 2026.01.08 |
| 파이썬 기본 문법 (0) | 2026.01.06 |
| 파이썬 기본 문법 (0) | 2026.01.05 |
| 2025년 보안 사고 정리 - SKT, 롯데카드, YES24, 쿠팡 (0) | 2026.01.01 |
