nullvuild

Bloger @nullvuild

Created Date '2025/02/20 오후 11:53

Modified Date '2025/02/21 오전 12:14

#SQLite #Python #sitemap #sqlite3

개요

이 문서는 Python으로 SQLite 데이터베이스에서 ID 값을 가져와 사이트맵(XML 형식)을 생성하는 Python 코드에 대한 설명을 제공한다.

이 코드를 실행하면 sitemap.xml 파일이 생성되며, 이를 검색 엔진 최적화(SEO)에 활용할 수 있다.


필요 라이브러리

다음과 같은 Python 내장 라이브러리를 사용한다.

  • sqlite3: SQLite 데이터베이스에서 데이터를 조회하는 데 사용
  • xml.etree.ElementTree: XML 파일을 생성하는 데 사용
  • xml.dom.minidom: XML을 사람이 읽기 쉽게 포맷팅하는 데 사용
  • os: 경로 설정 및 파일 관리

코드

import os
import sqlite3
import xml.etree.ElementTree as ET
import xml.dom.minidom  # XML 예쁘게 만들기 위한 모듈

# 상대 경로 설정
script_dir = os.path.dirname(os.path.abspath(__file__))  
db_path = os.path.abspath(os.path.join(script_dir, "..", "..", "test.sqlite3"))

# 사이트맵 기본 URL
base_url = "https://example.com/page/"

def fetch_ids_from_db(db_path, table_name):
    """SQLite에서 ID만 가져오기"""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(f"SELECT id FROM {table_name}")
    rows = cursor.fetchall()
    conn.close()
    return [row[0] for row in rows]

def create_sitemap_xml(ids, base_url):
    """ID 리스트를 사이트맵 XML 생성"""
    urlset = ET.Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")

    for id in ids:
        url_elem = ET.SubElement(urlset, "url")
        loc = ET.SubElement(url_elem, "loc")
        loc.text = f"{base_url}{id}"

    # XML을 문자열로 변환
    rough_string = ET.tostring(urlset, encoding='utf-8')
    reparsed = xml.dom.minidom.parseString(rough_string)  # XML 정리
    return reparsed.toprettyxml(indent="    ") # 들여쓰기 4칸 적용

# 실행
table_name = "pages"
ids = fetch_ids_from_db(db_path, table_name)
sitemap_xml = create_sitemap_xml(ids, base_url)

# XML 파일 저장
sitemap_path = os.path.join(script_dir, "sitemap.xml")
with open(sitemap_path, "w", encoding="utf-8") as f:
    f.write(sitemap_xml)

print(f"사이트맵 생성 완료: {sitemap_path}")

    
Nullvuild

Nullvuild

@nullvuild

프로필