Debian Codegraph @

examples/hack21.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2
3 # Port of Hack 21 from the O'Reilly book "Spidering Hacks" by Tara
4 # Calishain and Kevin Hemenway. Of course, there's no need to explicitly
5 # catch exceptions in Python, unlike checking error return values in Perl,
6 # but I've left those in for the sake of a direct port.
7
8 from __future__ import print_function
9 import sys
10 import os
11 import re
12
13 import mechanize
14 from mechanize.polyglot import HTTPError
15
16 mech = mechanize.Browser()
17 # Addition 2005-01-05: Be naughty, since robots.txt asks not to
18 # access /search now. We're not madly searching for everything, so
19 # I don't feel too guilty.
20 mech.set_handle_robots(False)
21 # mech.set_debug_http(True)
22
23 # Get the starting search page
24 try:
25 mech.open("http://search.cpan.org")
26 except HTTPError as e:
27 sys.exit("%d: %s" % (e.code, e.msg))
28
29 # Select the form, fill the fields, and submit
30 mech.select_form(nr=0)
31 mech["query"] = "Lester"
32 mech["mode"] = ["author"]
33 try:
34 mech.submit()
35 except HTTPError as e:
36 sys.exit("post failed: %d: %s" % (e.code, e.msg))
37
38 # Find the link for "Andy"
39 try:
40 mech.follow_link(text_regex=re.compile("Andy"))
41 except HTTPError as e:
42 sys.exit("post failed: %d: %s" % (e.code, e.msg))
43
44 # Get all the tarballs
45 urls = [link.absolute_url for link in
46 mech.links(url_regex=re.compile(r"\.tar\.gz$"))]
47 print("Found", len(urls), "tarballs to download")
48
49 if "--all" not in sys.argv[1:]:
50 urls = urls[:1]
51
52 for url in urls:
53 filename = os.path.basename(url)
54 f = open(filename, "wb")
55 print("%s -->" % filename, end=' ')
56 r = mech.open(url)
57 while 1:
58 data = r.read(1024)
59 if not data:
60 break
61 f.write(data)
62 f.close()
63 print(os.stat(filename).st_size, "bytes")