-
Notifications
You must be signed in to change notification settings - Fork 1
/
urlrulz.py
executable file
·51 lines (43 loc) · 1.46 KB
/
urlrulz.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
#!/usr/bin/env python3
"""Simple URL tester.
Reads lines in `urlz.txt` as `url [content]` and checks them all.
See sample `urlz.txt` file.
Filename(s) can also be specified on the command line.
The base urllib exception is catched to nicely display errors of type:
* Bad server name,
* 404,
* ...
"""
import sys
from urllib import request
from urllib.error import URLError
def check(filename='urlz.txt'):
"Check URLs in the given file."
for line in open(filename).read().split('\n'):
splitted_line = line.split(' ', 1)
if len(splitted_line) == 1:
url, expected_content = splitted_line[0], None
else:
url, expected_content = splitted_line
if not url or url.startswith('#'):
continue
print("Testing {}...".format(url))
if expected_content is not None:
expected_content = expected_content.lstrip()
actual_content = request.urlopen(url).read().decode("utf-8").rstrip('\n')
if actual_content != expected_content:
tpl = """At {}, expected \n'{}' but got \n'{}'"""
print(tpl.format(url, expected_content, actual_content))
break
else:
try:
request.urlopen(url)
except URLError as e:
print(e)
break
if __name__ == '__main__':
if len(sys.argv) == 1:
check()
else:
for filename in sys.argv[1:]:
check(filename)