-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathqueries.py
More file actions
138 lines (110 loc) · 5.48 KB
/
queries.py
File metadata and controls
138 lines (110 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
""" Contains all queries to Realtor.ca using undetected-chromedriver. """
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time
def scrape_property_list(city, max_pages=1):
"""Scrapes properties from Realtor.ca for a given city.
Args:
city: City name (e.g., "Toronto, ON")
max_pages: Maximum number of pages to scrape (default: 1)
Returns:
List of property dictionaries
"""
properties = []
driver = None
try:
print("🚀 Starting undetected Chrome browser...")
driver = uc.Chrome(version_main=145)
# Navigate to realtor.ca
print("📄 Loading realtor.ca...")
driver.get("https://www.realtor.ca")
time.sleep(5)
# Wait for search bar to load and interact with it
print("🔍 Looking for search bar...")
search_box = driver.find_element(By.XPATH, "//*[@id='homeSearchTxt']")
print("✓ Found search bar")
# Click on the search box and type the requested city
search_box.click()
time.sleep(1)
search_box.send_keys(city)
print(f"✓ Typed '{city}'")
# Press down arrow
search_box.send_keys(Keys.DOWN)
print("✓ Pressed down arrow")
time.sleep(1)
# Press Enter
search_box.send_keys(Keys.RETURN)
print("✓ Pressed Enter")
time.sleep(5)
for page in range(1, max_pages + 1):
print(f"\n📄 Processing page {page}...")
try:
# Wait for page to load
time.sleep(3)
# Get the rendered HTML
html_content = driver.page_source
soup = BeautifulSoup(html_content, 'html.parser')
# Find all property cards
property_cards = soup.find_all('div', class_='smallListingCard')
if not property_cards:
print(f"⚠ No properties found on page {page}")
break
print(f"✓ Found {len(property_cards)} properties on page {page}")
# Extract property information from each card
for idx, card in enumerate(property_cards, 1):
try:
# Extract address
address_elem = card.find('div', class_='smallListingCardAddress')
address = address_elem.get_text(strip=True) if address_elem else "N/A"
# Extract price
price_elem = card.find('div', class_='smallListingCardPrice')
price = price_elem.get_text(strip=True) if price_elem else "N/A"
# Extract bedroom, bathroom, sqft (from icon numbers)
icon_nums = card.find_all('div', class_='smallListingCardIconNum')
bedrooms = icon_nums[0].get_text(strip=True) if len(icon_nums) > 0 else "N/A"
bathrooms = icon_nums[1].get_text(strip=True) if len(icon_nums) > 1 else "N/A"
sqft = icon_nums[2].get_text(strip=True) if len(icon_nums) > 2 else "N/A"
# Extract link
link_elem = card.find('a', class_='blockLink')
link = link_elem.get('href') if link_elem else "N/A"
full_link = link if link.startswith('http') else f"https://www.realtor.ca{link}"
# Extract MLS number
mls_elem = card.find('div', class_='smallListingCardMLSVal')
mls = mls_elem.get_text(strip=True) if mls_elem else "N/A"
properties.append({
"Address": address,
"Bedrooms": bedrooms,
"Bathrooms": bathrooms,
"SquareFootage": sqft,
"Price": price,
"MLS": mls,
"Link": full_link
})
except Exception as e:
print(f"⚠ Error extracting property {idx}: {e}")
continue
# Click next page button if there are more pages
if page < max_pages:
try:
print(f"\n⏳ Going to page {page + 1}...")
next_button = driver.find_element(By.CLASS_NAME, "lnkNextResultsPage")
next_button.click()
time.sleep(8) # Wait longer for next page to load
except Exception as e:
print(f"⚠ No next page button found: {e}")
break
except Exception as e:
print(f"❌ Error processing page {page}: {e}")
if page == 1:
break
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
finally:
if driver:
print("\n🛑 Closing browser...")
driver.quit()
return properties