File size: 7,421 Bytes
4fd0f09
 
 
35645b4
 
4fd0f09
 
 
 
 
 
 
 
35645b4
a154445
 
 
 
35645b4
4fd0f09
35645b4
4fd0f09
 
 
 
 
 
 
 
 
 
 
35645b4
a154445
 
4fd0f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35645b4
a154445
4fd0f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import streamlit as st
import pandas as pd
import time
import os
import subprocess
import chromedriver_autoinstaller
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def install_chrome():
    if not os.path.exists("/usr/bin/chromium-browser"):
        subprocess.run(["apt-get", "update"], check=True)
        subprocess.run(["apt-get", "install", "-y", "chromium-browser"], check=True)
    os.environ["PATH"] += os.pathsep + "/usr/bin/"

def scrape_redfin(zipcode):
    install_chrome()  # Ensure Chrome/Chromium is installed
    chromedriver_autoinstaller.install()  # Ensure the correct chromedriver version is installed
    
    options = Options()
    options.add_argument("--headless")  # Run in headless mode
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--incognito")
    options.add_argument("--disable-blink-features=AutomationControlled")
    options.add_argument("start-maximized")
    options.add_argument("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")
    
    options.binary_location = "/usr/bin/chromium-browser"  # Use Chromium
    service = Service(chromedriver_autoinstaller.install())
    driver = webdriver.Chrome(service=service, options=options)
    url = f"https://www.redfin.com/zipcode/{zipcode}"
    driver.get(url)
    
    try:
        listings_container = WebDriverWait(driver, 60).until(
            EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[6]/div[1]/div[3]/div[1]/div[4]/div/div[1]/div"))
        )
    except Exception as e:
        st.error("Error: Listings did not load properly")
        driver.quit()
        return pd.DataFrame()
    
    scroll_pause_time = 5  
    screen_height = driver.execute_script("return window.innerHeight;")
    last_height = driver.execute_script("return document.body.scrollHeight")
    
    while True:
        driver.execute_script("window.scrollBy(0, arguments[0]);", screen_height // 2)
        time.sleep(scroll_pause_time)
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height
    
    houses = []
    listings = driver.find_elements(By.XPATH, "/html/body/div[1]/div[6]/div[1]/div[3]/div[1]/div[4]/div/div[1]/div/div")
    
    for listing in listings:
        try:
            price = listing.find_element(By.XPATH, ".//div/div/div[2]/div[1]/div[1]/span").text
        except:
            price = "N/A"
        
        try:
            address = listing.find_element(By.XPATH, ".//div/div/div[2]/div[3]").text
        except:
            address = "N/A"
        
        try:
            size = listing.find_element(By.XPATH, ".//div/div/div[2]/div[4]/div").text
        except:
            size = "N/A"
        
        try:
            link = listing.find_element(By.TAG_NAME, "a").get_attribute("href")
        except:
            link = "N/A"
        
        houses.append({"Price": price, "Address": address, "Size": size, "Link": link})
    
    driver.quit()
    return pd.DataFrame(houses)

st.title("Redfin House Listings Scraper")
zipcode = st.text_input("Enter ZIP code:")

if st.button("Scrape Data"):
    if zipcode:
        with st.spinner("Scraping data, please wait..."):
            df = scrape_redfin(zipcode)
            if not df.empty:
                st.success("Scraping complete! Here are the available houses:")
                st.dataframe(df)
            else:
                st.warning("No houses found for the given ZIP code.")
    else:
        st.error("Please enter a valid ZIP code.")














## working best code ever

# import streamlit as st
# import pandas as pd
# import time
# from selenium import webdriver
# from selenium.webdriver.common.by import By
# from selenium.webdriver.chrome.service import Service
# from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
# from webdriver_manager.chrome import ChromeDriverManager

# def scrape_redfin(zipcode):
#     options = Options()
#     options.add_argument("--headless")
#     options.add_argument("--incognito")
#     options.add_argument("--disable-blink-features=AutomationControlled")
#     options.add_argument("start-maximized")
#     options.add_argument("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")
    
#     driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
#     url = f"https://www.redfin.com/zipcode/{zipcode}"
#     driver.get(url)
    
#     try:
#         listings_container = WebDriverWait(driver, 60).until(
#             EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[6]/div[1]/div[3]/div[1]/div[4]/div/div[1]/div"))
#         )
#     except Exception as e:
#         st.error("Error: Listings did not load properly")
#         driver.quit()
#         return pd.DataFrame()
    
#     scroll_pause_time = 5  
#     screen_height = driver.execute_script("return window.innerHeight;")
#     last_height = driver.execute_script("return document.body.scrollHeight")
    
#     while True:
#         driver.execute_script("window.scrollBy(0, arguments[0]);", screen_height // 2)
#         time.sleep(scroll_pause_time)
#         new_height = driver.execute_script("return document.body.scrollHeight")
#         if new_height == last_height:
#             break
#         last_height = new_height
    
#     houses = []
#     listings = driver.find_elements(By.XPATH, "/html/body/div[1]/div[6]/div[1]/div[3]/div[1]/div[4]/div/div[1]/div/div")
    
#     for listing in listings:
#         try:
#             price = listing.find_element(By.XPATH, ".//div/div/div[2]/div[1]/div[1]/span").text
#         except:
#             price = "N/A"
        
#         try:
#             address = listing.find_element(By.XPATH, ".//div/div/div[2]/div[3]").text
#         except:
#             address = "N/A"
        
#         try:
#             size = listing.find_element(By.XPATH, ".//div/div/div[2]/div[4]/div").text
#         except:
#             size = "N/A"
        
#         try:
#             link = listing.find_element(By.TAG_NAME, "a").get_attribute("href")
#         except:
#             link = "N/A"
        
#         houses.append({"Price": price, "Address": address, "Size": size, "Link": link})
    
#     driver.quit()
#     return pd.DataFrame(houses)

# st.title("Redfin House Listings Scraper")
# zipcode = st.text_input("Enter ZIP code:")

# if st.button("Scrape Data"):
#     if zipcode:
#         with st.spinner("Scraping data, please wait..."):
#             df = scrape_redfin(zipcode)
#             if not df.empty:
#                 st.success("Scraping complete! Here are the available houses:")
#                 st.dataframe(df)
#             else:
#                 st.warning("No houses found for the given ZIP code.")
#     else:
#         st.error("Please enter a valid ZIP code.")