[파이썬] 웹 스크래핑과 부동산 정보 추출

웹 스크래핑은 인터넷 상의 웹 페이지에서 데이터를 추출하는 기술입니다. 이를 통해 다양한 정보를 수집하고 분석할 수 있습니다. 이번 포스트에서는 웹 스크래핑을 사용하여 부동산 정보를 추출하는 방법에 대해 알아보겠습니다.

라이브러리 설치

웹 스크래핑을 위해서는 Python을 사용해야 합니다. 또한, 웹 스크래핑에는 다양한 라이브러리들이 존재합니다. 이번 포스트에서는 requests와 BeautifulSoup 라이브러리를 사용하여 웹 페이지에 접근하고 HTML을 파싱할 것입니다.

다음과 같이 두 개의 라이브러리를 설치할 수 있습니다:

pip install requests beautifulsoup4

웹 페이지에 접근하기

requests 라이브러리를 사용하여 웹 페이지에 접근할 수 있습니다. 다음은 예제 코드입니다:

import requests

url = "https://www.example.com"
response = requests.get(url)

if response.status_code == 200:
    print("Success")
else:
    print("Failed to access the web page")

위 코드를 실행하면 https://www.example.com 웹 페이지에 접근하여 응답을 받습니다. 응답의 상태 코드가 200인 경우에만 “Success”가 출력됩니다.

HTML 파싱하기

BeautifulSoup 라이브러리를 사용하여 HTML을 파싱할 수 있습니다. 파싱된 HTML에서 원하는 정보를 추출할 수 있습니다. 다음은 예제 코드입니다:

from bs4 import BeautifulSoup

# HTML 코드 예제
html = """
<html>
<head>
    <title>Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is an example paragraph.</p>
</body>
</html>
"""

soup = BeautifulSoup(html, "html.parser")
title = soup.title.string
paragraph = soup.p.string

print("Title: ", title)
print("Paragraph: ", paragraph)

위 코드를 실행하면 html 변수에 저장된 HTML 코드를 파싱하여 제목과 문단을 추출합니다. 그 결과는 다음과 같이 출력됩니다:

Title:  Example
Paragraph:  This is an example paragraph.

부동산 정보 추출하기

이제 웹 스크래핑을 사용하여 부동산 정보를 추출해보겠습니다. 예를 들어, 직방 웹 사이트에서 원하는 지역의 매물 정보를 추출해보겠습니다.

import requests
from bs4 import BeautifulSoup

# 웹 페이지에 접근
url = "https://www.zigbang.com/search/map?coords=37.56629538671879,126.97279288861692,14&zbType=ma"
response = requests.get(url)

if response.status_code == 200:
    # HTML 파싱
    soup = BeautifulSoup(response.content, "html.parser")
    
    # 부동산 정보 추출
    listings = soup.select(".list-item")
    
    for listing in listings:
        title = listing.select_one(".list-item-title").text.strip()
        address = listing.select_one(".list-item-address").text.strip()
        price = listing.select_one(".list-item-price").text.strip()
        
        print("Title: ", title)
        print("Address: ", address)
        print("Price: ", price)
        print()
else:
    print("Failed to access the web page")

위 코드를 실행하면 지역 정보에 해당하는 부동산 매물의 제목, 주소, 가격을 출력합니다. 해당 부동산 정보는 클래스명으로 추출하였습니다.

이제 웹 스크래핑을 통해 부동산 정보를 추출하는 방법을 알게 되었습니다. 웹 스크래핑은 다양한 데이터를 수집하고 활용할 수 있는 강력한 도구입니다.