Zillow에서 부동산 정보를 추출하면 시장과 투자에 대한 완벽한 분석을 제공할 수 있습니다. 이 글에서는 Python으로 Zillow 매물 목록을 스크랩하는 데 필요한 필수 단계와 지침을 중점적으로 다룹니다. 이 가이드에서는 요청 및 lxml과 같은 라이브러리를 사용하여 Zillow 웹사이트에서 정보를 스크랩하는 방법을 보여드립니다.
시작하기 전에 시스템에 Python이 설치되어 있는지 확인하세요. 또한 다음 라이브러리도 설치해야 합니다:
pip install requests
pip install lxml
Zillow에서 데이터를 추출하려면 웹 페이지의 구조를 이해해야 합니다. Zillow에서 부동산 목록 페이지를 열고 스크랩하려는 요소(예: 부동산 제목, 임대료 예상 가격, 평가 가격)를 검사합니다.
Title:
가격 세부 정보:
이제 HTTP 요청을 전송해 보겠습니다. 먼저 Zillow 페이지의 HTML 콘텐츠를 가져와야 합니다. 요청 라이브러리를 사용하여 대상 URL에 HTTP GET 요청을 보내겠습니다. 또한 실제 브라우저 요청을 모방하도록 요청 헤더를 설정하고 프록시를 사용하여 IP 차단을 피할 것입니다.
import requests
# Zillow 부동산 목록의 대상 URL을 정의합니다.
url = "https://www.zillow.com/homedetails/1234-Main-St-Some-City-CA-90210/12345678_zpid/"
# 브라우저 요청을 모방하도록 요청 헤더를 설정합니다.
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 선택 사항으로 프록시를 설정하여 IP 차단을 피하세요.
proxies = {
'http': 'http://username:password@your_proxy_address',
'https://username:password@your_proxy_address',
}
# 헤더 및 프록시와 함께 HTTP GET 요청을 전송합니다.
response = requests.get(url, headers=headers, proxies=proxies)
response.raise_for_status() # Ensure we got a valid response
다음으로 lxml을 사용하여 HTML 콘텐츠를 구문 분석해야 합니다. lxml.html 모듈의 fromstring 함수를 사용하여 웹 페이지의 HTML 콘텐츠를 Element 객체로 구문 분석합니다.
from lxml.html import fromstring
# lxml을 사용하여 HTML 콘텐츠 구문 분석
parser = fromstring(response.text)
이제 구문 분석된 HTML 콘텐츠에서 XPath 쿼리를 사용하여 부동산 제목, 임대료 예상 가격 및 평가 가격과 같은 특정 데이터 요소를 추출합니다.
# XPath를 사용하여 속성 제목 추출하기
title = ' '.join(parser.xpath('//h1[@class="Text-c11n-8-99-3__sc-aiai24-0 dFxMdJ"]/text()'))
# XPath를 사용하여 부동산 임대료 예상 가격 추출하기
rent_estimate_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-2]
# XPath를 사용하여 부동산 평가 가격 추출하기
assessment_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-1]
# 추출된 데이터를 사전에 저장
property_data = {
'title': title,
'Rent estimate price': rent_estimate_price,
'Assessment price': assessment_price
}
마지막으로 추가 처리를 위해 추출된 데이터를 JSON 파일에 저장합니다.
import json
# 출력 JSON 파일 이름 정의
output_file = 'zillow_properties.json'
# 쓰기 모드에서 파일을 열고 데이터를 덤프합니다.
with open(output_file, 'w') as f:
json.dump(all_properties, f, indent=4)
print(f"Scraped data saved to {output_file}")
여러 속성 목록을 스크랩하려면 URL 목록을 반복하고 각 목록에 대해 데이터 추출 프로세스를 반복합니다.
# 스크랩할 URL 목록
urls = [
"https://www.zillow.com/homedetails/1234-Main-St-Some-City-CA-90210/12345678_zpid/",
"https://www.zillow.com/homedetails/5678-Another-St-Some-City-CA-90210/87654321_zpid/"
]
# 모든 속성에 대한 데이터를 저장할 목록
all_properties = []
for url in urls:
# 헤더 및 프록시와 함께 HTTP GET 요청을 전송합니다.
response = requests.get(url, headers=headers, proxies=proxies)
response.raise_for_status() # Ensure we got a valid response
# lxml을 사용하여 HTML 콘텐츠 구문 분석
parser = fromstring(response.text)
# XPath를 사용하여 데이터 추출
title = ' '.join(parser.xpath('//h1[@class="Text-c11n-8-99-3__sc-aiai24-0 dFxMdJ"]/text()'))
rent_estimate_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-2]
assessment_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-1]
# 추출된 데이터를 사전에 저장
property_data = {
'title': title,
'Rent estimate price': rent_estimate_price,
'Assessment price': assessment_price
}
# 목록에 속성 데이터 추가
all_properties.append(property_data)
다음은 Zillow 속성 데이터를 스크랩하여 JSON 파일에 저장하는 전체 코드입니다:
import requests
from lxml.html import fromstring
import json
# Zillow 부동산 목록의 대상 URL 정의하기
urls = [
"https://www.zillow.com/homedetails/1234-Main-St-Some-City-CA-90210/12345678_zpid/",
"https://www.zillow.com/homedetails/5678-Another-St-Some-City-CA-90210/87654321_zpid/"
]
# 브라우저 요청을 모방하도록 요청 헤더를 설정합니다.
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-US,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'sec-ch-ua': '"Not/A)Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
'sec-ch-ua-mobile': '?0',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
# 선택 사항으로 프록시를 설정하여 IP 차단을 피하세요.
proxies = {
'http': 'http://username:password@your_proxy_address',
'https': 'https://username:password@your_proxy_address',
}
# 모든 속성에 대한 데이터를 저장할 목록
all_properties = []
for url in urls:
try:
# 헤더 및 프록시와 함께 HTTP GET 요청을 전송합니다.
response = requests.get(url, headers=headers, proxies=proxies)
response.raise_for_status() # Ensure we got a valid response
# lxml을 사용하여 HTML 콘텐츠 구문 분석
parser = fromstring(response.text)
# XPath를 사용하여 데이터 추출
title = ' '.join(parser.xpath('//h1[@class="Text-c11n-8-99-3__sc-aiai24-0 dFxMdJ"]/text()'))
rent_estimate_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-2]
assessment_price = parser.xpath('//span[@class="Text-c11n-8-99-3__sc-aiai24-0 dFhjAe"]//text()')[-1]
# 추출된 데이터를 사전에 저장
property_data = {
'title': title,
'Rent estimate price': rent_estimate_price,
'Assessment price': assessment_price
}
# 목록에 속성 데이터 추가
all_properties.append(property_data)
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
# 출력 JSON 파일 이름 정의
output_file = 'zillow_properties.json'
# 쓰기 모드에서 파일을 열고 데이터를 덤프합니다.
with open(output_file, 'w') as f:
json.dump(all_properties, f, indent=4)
print(f"Scraped data saved to {output_file}")
HTML 페이지의 구조를 이해하고 요청 및 lxml과 같은 강력한 라이브러리를 활용하면 매물 세부 정보를 효율적으로 추출할 수 있습니다. 프록시와 로테이션 사용자 에이전트를 사용하면 차단될 위험 없이 Zillow와 같은 사이트에 대량의 요청을 할 수 있습니다. 이러한 활동에는 정적 ISP 프록시 또는 로테이션 주거용 프록시가 최적의 선택으로 간주됩니다.
댓글: 0