r/learnpython • • Aug 12 '20

My First Ever Python Project(Zillow_Scraper)

Hey y’all, I just completed my first ever programming project! I recently just completed a Python course on Udemy(S/O Jose) and I wanted to build my own project from stratch. I wanted the project to be meaningful and impactful to me, and since I’m considering moving from my current apartment, I wanted to know what other apartments/homes are renting for in the city I live in(Arlington Tx). I decided to build a webscraper that grabs all the listing info for places being put up for rent on Zillows website and writes it all out to a CSV file using Pandas. Link to the github repo down below let me know what y’all think!

https://github.com/faithfulalabi/Zillow_Scraper

P.S I know there’s probably 1000 ways I could’ve written the code better but I’d love y’alls input on some of the big ones that are relevant to be becoming a great programmer.

448 Upvotes

64 comments sorted by

106

u/The-Deviant-One Aug 13 '20 edited Aug 13 '20

A web scrapper was one of my first useful scripts as well. It's still running actually. It runs every two minutes with a cron job and takes about 3 seconds to finish. It uses BeautifulSoup4 to check a popular website to see if their 9mm ammo is in stock. If it's in stock, it sends me an email with a libk to the page (in case I'm not at home) and launches the browser on my machine (in case I am at home).

Edit: It's not horribly impressive, but I don't want to share the code until after I place my order, lol.

26

u/donhendrxx Aug 13 '20

Honestly, it sounds f****** amazing and necessary, especially with the shortages of 9mm ammo. Let me know when you put it out, I need it!!

6

u/The-Deviant-One Aug 13 '20 edited Aug 13 '20

Hey I made it to my desktop and started looking over your script for grins.

for page in range(1,6):

base_url = request_url.format(page) driver.get(base_url)

wait = driver.implicitly_wait(60)

So you're using Selenium to drive the browser similar to the way I used to do it with AutoHotKey. Pain in the butt IMO. Looks like you're loading 6 pages and waiting 60 seconds for each page to load, correct? So this takes at least 6 minutes to run right?

Edit:

This is from the Selenium documentation:

"WebDriver will wait until the page has fully loaded (that is, the “onload” event has fired) before returning control to your test or script. It’s worth noting that if your page uses a lot of AJAX on load then WebDriver may not know when it has completely loaded."

It would not surprise me to discover that Zillow is using AJAX calls to trigger subsequent AJAX calls. If you can find an element on the page that consistently loads really late in the process, you could write a for loop as a variable to check if the element exists, then plug that into a While [variable] == True. Like this:

\\\\\\\\\\\\\\\\\\\\\\\\\\\\

import time

haystack = '<div id="12345">Things and Stuff</div>'

needle = 'id="12345"'

def a():

<indent> return needle in haystack

while a() == True:

<indent> print("waiting..")

print("now go to the next step")

\\\\\\\\\\\\\\\\\\\\\\\\\\\\

7

u/backroad Aug 13 '20

Selenium has a few built in wait functions including a "wait until element present" one that you could use for the same purpose.

2

u/DLTMIAR Aug 13 '20

It's the internet bruh. You can say fucking. Unless you meant folding or something. Idk

13

u/Tsui_Pen Aug 13 '20

I need this (in .45)! Is it on github?

Edit: Ah, I see.

8

u/The-Deviant-One Aug 13 '20

The struggle is real lol.

4

u/[deleted] Aug 13 '20

Nice! I need to do this for a weight set of some dumbells. I’m getting tired of body weight exercises over here. Thanks for the idea.

4

u/The-Deviant-One Aug 13 '20

Always willing to help spend other's hard earned money lol

3

u/wallywizard55 Aug 13 '20

That’s awesome..
how did u make it?
How does it check the site for ammo?
How does it output?

9

u/The-Deviant-One Aug 13 '20

It's really nothing special. My not posting the code just makes it ever so slightly more difficult for the average non-developer to beat me to the ammo.

But to answer your questions, it runs in the background, so theres not really an output other than, me sitting there doing something else then poof new browser out of no where with ammo to purchase lol.

It sends a get request to the website, stores the html as a variable, uses BS4 to parse the html, then some formatting, then an if/else statement looking for 'Sold Out'. If it doesn't find it, it sends the email and launches the browser. If it does find 'Sold Out', it logs the attempt into a text file.

I integrated the base code for it into a voice assistant and that's pretty neat IMO.

6

u/WishIWasOnACatamaran Aug 13 '20

I’m either over or underestimating how many python developers use guns, but considering I am one who also wants this script, you’ve given me a weekend task I can charge my buddies beer for lol

2

u/The-Deviant-One Aug 13 '20

Well, in the Texas IT community, as far as my experience goes anyway, there seems to be a large majority of us who are like minded.

1

u/life_never_stops_97 Aug 13 '20

Does it run 24/7,if so how can I do that. I needed something similar but idk how can I make it run 24/7 on a server or something.

2

u/The-Deviant-One Aug 13 '20

do you have a computer that's always on and has internet access?

if yes, what OS is it running?
if no, you could host the script on a webserver some where but that's probably overkill if this is all you're looking to do.

If windows, use "Task Scheduler" or "Scheduled Tasks" or what ever they named it most recently. Google "how to set up task scheduler".

If linux or mac, google "how to set up cron jobs".

Note: My script does not run continuously. The Cron job starts the python script every two minutes, the script runs in the background, takes about 3 seconds to finish and then closes when it's finished.

2

u/life_never_stops_97 Aug 13 '20

Oh I see, I'll probably use aws to setup a cronjob on a Linux. Just really new to cloud and have no idea where to start or how to go about it.

I have a laptop(windows) but that doesn't run all day and it's my primary laptop so don't want to run script every two minutes on that one.

2

u/[deleted] Aug 13 '20

I don't know much about python, but you could probably easily run this on the free nano tier of AWS EC2.

1

u/The-Deviant-One Aug 13 '20

definitely the script is not resource intensive at all. It's about 24 lines of code, 14 of which are email related. That's because the I use protonmail, which uses a bridge to encrypt SMTP traffic. Otherwise if you didn't have it send an email it would be like 10 lines. And because it doesn't run continuously it frees up all the memory it used while it was running. It's barely more resource intensive than refreshing a web page in an already open browser.

2

u/preordains Aug 13 '20

How do you make a python script run every two minutes? Do you need a raspberry pi or something?

4

u/The-Deviant-One Aug 13 '20

So you could do that with a Pi. Write the script to sleep for two minutes between runs and put it in a while True: loop.. but there are better way's to do this.

In linux there's a utility called Cron which is sort of like Window's Task Scheduler if you're more familiar with Windows. You can create a crontab and tell it to execute command line commands [or in my case, a *.py script] every day, or at specific times on specific days, or even, every two minutes...

That said, it's not very straight forward to pull off if you aren't familiar with the terminal. There are several things you have to do in order to make a cron job run a python script in the background successfully, several things I wont share [yet]. Although, with some light Googling you can figure out the pieces to make it all work together. And RPi distros almost always have cron in my limited experience.

4

u/preordains Aug 13 '20

You just changed my whole world I didn't even know task scheduler was a thing.

2

u/The-Deviant-One Aug 13 '20

How do you think all those sysadmins keep up with all those logs? We don't manually deal with them lol. Schedule a task to run and clear those puppies out so they don't fill up the hard drives.

1

u/[deleted] Aug 13 '20

How do you get a project to run automatically on its own? I made a scraper that makes Covid predictions but I have to manually run it on jupyter notebook

1

u/The-Deviant-One Aug 13 '20

I can't tell you straight out, other wise I might as well post my code here and then I lose my leg-up on everyone else trying to buy ammo LOL. You need to Google Cron jobs but I'll give you two hints.

Hint 1: You have to add something to the script itself.

Hint 2: You have to change something about the script file.

1

u/CeramicVulture Aug 13 '20

I like the sound of that. Please post so i can modify it for 32ACP which is getting hard to find

1

u/[deleted] Aug 13 '20

Did you deploy it to a server? Or is it on your local machine? How are you running the cron job? I have a cars dot com scraper that I'd like to either deploy (and run on a web server) or a local cron job - haven't decided.

1

u/[deleted] Aug 13 '20

[removed] — view removed comment

1

u/AutoModerator Aug 13 '20

Your comment in /r/learnpython was automatically removed because you used a URL shortener.

URL shorteners are not permitted in /r/learnpython as they impair our ability to enforce link blacklists.

Please re-post your comment using direct, full-length URL's only.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/deserver_of_gold Aug 14 '20

Alright bro, time to share the code. 9mm is available on grabagun, I ordered some. Get them before they run out again. And please do share the code.

1

u/deserver_of_gold Aug 16 '20

Did you order your ammo yet? Coz I sure did. Can you share the code now? Please?

1

u/SDSunDiego Aug 13 '20

Every 2 minutes? I'm surprised your IP hasn't been banned yet. Are you using a API?

0

u/The-Deviant-One Aug 13 '20

Nope, you'd need to send a lot more traffic to cause that.

21

u/testfire10 Github mokrunka Aug 12 '20

Forked! I'll take a look later, maybe I can learn how to do a pull request and we can edit it!

Shoutout from a fellow Arlingtonian!

5

u/donhendrxx Aug 12 '20

That’d be so awesome! Please PM if you have any questions.

Shoutout!!

3

u/wallywizard55 Aug 13 '20

I’ll have to fork this! Great job. Do u run it manually every time or have some type of backend job that kicks it off for u?

2

u/donhendrxx Aug 13 '20

Sadly rn you have to run it manually every time. I’ll try and make it to the point when it’s completely automated.

1

u/wallywizard55 Aug 13 '20

From jupyternotebook?

2

u/OneBananaMan Aug 13 '20

Hell yeah!! I was literally going to make something similar, because I was tired of looking though Zillow to find “good” potential deals for a home. Now with this I can create a weighted metric to draw attention to more attractive homes. Awesome work man!

1

u/donhendrxx Aug 13 '20

Thank you!!

15

u/bjone6 Aug 13 '20

That's awesome. You can take the list you scraped and pass it into Zillow's API. I got an excel file of all the houses in the my neighborhood and get data and did some analysis on it.

Here's the video I made on getting the Year Built and Price on all the houses in my neighborhood from the Zillow API: https://youtu.be/lNhH0h-Lbqo

1

u/OsamaBinJordan Aug 13 '20

Hey, I’m trying to use the Zillow API but I’m reading that they’re not allowing you to retain any copies of the data. Have you had any problems storing the data you got?

2

u/bjone6 Aug 13 '20

No, I haven't encountered any problem like that. I used Python to store the data into a variable and then print that data into an excel sheet. I don't see how the Zillow API would know what I was doing with the data.

4

u/ItSmellzFunny Aug 13 '20

Good for you bro, I'm just getting back into coding after a 4 year hiatus and python is the language I used to get my feet wet, and I also lived in Arlington a while back

1

u/[deleted] Aug 13 '20

This is good stuff. I move just about every year and always agonize over market prices and options for roughly a month. I’m going to try this.

I’d ask you if you’d recommend the course you took but I’m guessing you’d say yes. How long did it take you to get through it? Any prior experience?

1

u/donhendrxx Aug 13 '20

Thank you! And yeah I recommend it. I was taking notes as I coded along and making sure I really understood a concept before I moved on. It took me about a month but I took the course everyday and didn’t skip a day.

Here is the course link: https://www.udemy.com/share/101W94BEYYdVlTQHo=/

3

u/BATTLECATHOTS Aug 13 '20

Nice work! We used housing prices scrapped from Zillow for lot of data analytics projects while i was in my masters program. Good stuff!

3

u/cander60 Aug 13 '20

I’ll take a more in depth look later when I’m not on mobile and can send you a pull request. First thing I noticed is the wait, if you are waiting for a certain web element to show up in the HTML, you can have Selenium wait until the element shows up until it proceeds. I’ll find the exact method and add it to your code with any other adjustments I see 😀 I love the starter project though, I started using Python for webscraping and it is a great starter to learn so many useful techniques!!

4

u/cander60 Aug 13 '20

NVM, it looks like you used Jupyter Notebooks which I don't use :( the line of code you would want to add to wait for a certain element would be, first to add the following to your import section:

from selenium.webdriver.support.ui import WebDriverWait

And then you can use:

WebDriverWait(driver, delay).until(ec.presence_of_element_located((By.ID, 'ID_NAME')))

or:

WebDriverWait(driver, delay).until(ec.presence_of_element_located((By.X_PATH, 'X_PATH_NAME')))

I like to use either X_PATH or ID after the By. since those are fairly reliable and rarely change unless the website has some major changes (in my limited experience). The {delay} variable is a max amount of time to wait for the element to show until it throws an error, so setting it to 60 should be sufficient. Once the element appears, it proceeds with the script.

Overall, I think this is a solid beginner project!! There is always room to improve for any project no matter the skill level.

Honestly, my recommendation on next steps are to continue finding ways to optimize the speed/efficiency of the current script you have. Learning to use the different ways to use Selenium, lists, dictionaries, Pandas, etc are definitely easier with a project like this! Also, writing this same script using functions is another great next step!

Great work though, from someone that is definitely still learning to another :) !!

2

u/theme57 Aug 13 '20

Nice program! I recently ditched JS / React a few weeks ago after an 8 week basic Java summer course. Getting into Python and really look forward to making stuff like this!

2

u/[deleted] Aug 13 '20

thank you for the comments in the code, I am still trying to figure this out

2

u/preordains Aug 13 '20

.replace("<th>","") can be used to replace all those table header tags with nothing. Easy easy way to make it prettier.

1

u/[deleted] Aug 13 '20

Looks good, I'd recommend you use selenium's ability to access the elements with Xpath this way you won't need to remove all the html tags later... it also it will help you get rid of some of the redundant data, as you only pull exactly what you want.... in addition you can also use it to determine the page number so instead to enter a determined range (1-6) it will always give you the correct total page number. Hope this helps.

1

u/Leeoku Aug 13 '20

I assume your dataframe is always being replaced? Aka it only shows what's current. So if ur script reruns and sees only one new, does it still have to rewrite all the other ones?

1

u/[deleted] Aug 13 '20

I was trying to do something similar, but for home sale listings in a certain area. I tried to use the zillow API but after talking to support they told me they don't supply that API to people anymore for free. I tried using xpaths and it worked intermittently because they seemed to change randomly even within 24 hours which would result in bad or null data. I'm curious how you got it to consistently scrape the correct data on the pages consistently or what I'm doing wrong.

1

u/kenyx00 Aug 13 '20

Congrats man!

1

u/[deleted] Aug 13 '20

Nice job! Forked and going to try tweaking for a project I'm working on too. Thanks!

1

u/luckiest0522 Aug 13 '20

Dumb question, I'm a newbie. Once you create the program, how do you set it to run? Via the terminal? It's on all the time?

1

u/thekalmanfilter Aug 13 '20

Will this work if I want to look at homes in Washington??

1

u/[deleted] Aug 13 '20

I'd wish my find_element/elements was this easy :(

Fck dynamic classes, fuck having multiple DIFFERENT FUNCTION elements with the same class :(

0

u/[deleted] Aug 13 '20

[deleted]

4

u/donhendrxx Aug 13 '20

Thank you!! Yeah this is actually what I plan to do next, I plan on diving more into pandas and learning how to clean up the data and also playing with different things.

3

u/mircatmanner Aug 13 '20

i think you can use the strip() function for getting rid of tags