-
Notifications
You must be signed in to change notification settings - Fork 0
/
craigwatcher.py
52 lines (45 loc) · 1.87 KB
/
craigwatcher.py
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
from bs4 import BeautifulSoup
import os
import requests
import smtplib
from email.mime.text import MIMEText
# Retrieve the entire relevant CL site.
url = 'http://sfbay.craigslist.org/search/apa/sfc?query=&srchType=A&minAsk=1500&maxAsk=4000&bedrooms=3&nh=1&nh=3&nh=8&nh=18&nh=25'
html_doc = requests.get(url)
# Initialize the soup.
post_soup = BeautifulSoup(html_doc.text, 'html5lib')
# Remember the old posts.
old_posts = []
old_postings = '/home/ec2-user/craigslist/old_postings.txt'
with open(old_postings,'r') as old_posts_file:
old_posts = old_posts_file.readlines()
# Initialize a list for the new posts.
new_posts = []
# Iterate through posts to find novelties.
for post in post_soup.find_all('p','row'):
# Retrieve the URL for the post.
posting_url = post.find('a')['href'].encode('ascii','ignore')
# See if it's new.
if posting_url+'\n' not in old_posts:
# It's new! Gather its data.
price = post.find('span','itemph').text.encode('ascii','ignore')
title = post.find('a').text.encode('ascii','ignore')
# Remember it for later.
with open(old_postings,'a') as oldies:
oldies.write(posting_url+'\n')
# Format it all pretty-like
post_content = '{price} <a href="{url}">{title}</a>'.format(price=price, url=posting_url, title=title)
new_posts.append(post_content)
# Output for debugging
print posting_url
# Finished searching.
# Send out the new posts via email.
if len(new_posts) > 0:
msg = MIMEText('<br />'.join(new_posts), 'html')
msg['Subject'] = 'New Craigslist postings'
msg['from'] = 'Craigwatcher'
msg['to'] = ','.join(recipients)
s = smtplib.SMTP('localhost')
s.sendmail('[email protected]',recipients,msg.as_string())
s.quit()