urlwatch 1.1
[urlwatch.git] / watch.py
blob20be4562ba75e1862e7a471abeb6b05b2ea9eef4
1 #!/usr/bin/python
2 # Minimalistic Python URL watcher
3 # 2008-03-04 Thomas Perl <thpinfo.com>
4 # http://thpinfo.com/2008/urlwatch
6 # 1. Create an "urls.txt" file and add one URL per
7 # line that you want to watch.
8 # 2. Add watch.py as a cronjob or run it manually.
9 # 3. If something changed, you'll get a diff output
10 # to stdout. If nothing changed, no output.
11 # 4. If you want to filter the web pages, because
12 # there is some dynamic content that _always_
13 # changes, create a "hooks.py" file that has a
14 # filter(url, data) -> filtered_data function
16 # Configuration section
17 display_errors = False
19 # Code section
21 import sha
22 import sys
23 import os.path
24 import urllib2
25 import difflib
27 os.chdir(os.path.dirname(sys.argv[0]))
29 if os.path.exists('hooks.py'):
30 from hooks import filter
31 else:
32 filter = lambda x, y: y
34 for url in (x for x in open('urls.txt').read().splitlines() if not (x.startswith('#') or x.strip()=='')):
35 filename = sha.new(url).hexdigest()
36 try:
37 data = filter(url, urllib2.urlopen(url).read())
38 if os.path.exists(filename):
39 old_data = open(filename).read()
40 diff = ''.join(difflib.unified_diff(old_data.splitlines(1), data.splitlines(1)))
41 if len(diff) > 0:
42 print '%s\nCHANGED: %s\n%s\n%s\n%s\n\n' % ('*'*60, url, '*'*60, diff, '*'*60)
43 else:
44 print '%s\nNEW: %s\n%s\n\n' % ('*'*60, url, '*'*60)
45 open(filename, 'w').write(data)
46 except urllib2.HTTPError, error:
47 if display_errors:
48 print '%s\nERROR: %s\n%s\n%s\n%s\n\n' % ('*'*60, url, '*'*60, error, '*'*60)
49 except urllib2.URLError, error:
50 if display_errors:
51 print '%s\nERROR: %s\n%s\n%s\n%s\n\n' % ('*'*60, url, '*'*60, error, '*'*60)