에코프로.AI

PostgreSQL 설치 및 데이터 저장 (Feat. Python) 본문

AI Tutorial

PostgreSQL 설치 및 데이터 저장 (Feat. Python)

AI_HitchHiker 2024. 7. 31. 16:28

PostgreSQL & DBeaver 설치

PostgreSQL 다운로드 및 설치

  • 다운받으신 exe.파일을 실행하셔서 설치하시면 됩니다.

DBeaver 다운로드 및 설치

아래와 같은 화면이 표시되며, Windows / Max OS X 중 선택하셔서 다운로드 받습니다.

  • 다운받은 exe.파일을 실행하여 설치합니다.
  • PostgreSQL 접속

 

파이썬 데이터 PostgreSQL에 저장

PostgreSQL - 테이블 생성

create table tbl_crawl_data (
    cid serial primary key,
    title varchar(255),
    description TEXT,
    create_at timestamp default current_timestamp
);

라이브러리 설치

%pip install requests
%pip install BeautifulSoup
%pip install psycopg2

파이썬 코드

import requests
from bs4 import BeautifulSoup

# 웹 페이지에서 데이터 크롤링
def crawl_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # 예시로서 특정 데이터를 추출
    data = []
    for item in soup.find_all('div'):
        title = item.find('h1').text
        description = item.find('p').text

        data.append([title, description])

    return data

# 데이터 저장
import psycopg2

# PostgreSQL 데이터베이스에 연결
def connect_db():
    conn = psycopg2.connect(
        dbname = 'postgres',
        user = 'postgres',
        password = 'cslee',
        host = 'localhost',
        port = '5432'

    )
    return conn

# 데이터 삽입
def insert_data(conn, data):
    cursor = conn.cursor()
    insert_query = 'insert into cslee.tbl_crawl_data (title, description) values (%s, %s)'
    cursor.executemany(insert_query, data)
    conn.commit()
    cursor.close()
# 전체 프로세스 실행
def main():
    url = 'https://www.example.com'
    data = crawl_data(url)

    conn = connect_db()
    insert_data(conn, data)
    conn.close()

if __name__ == '__main__':
    main()

데이터 저장 확인