| 1 |
#!/usr/bin/env python
|
| 2 |
|
| 3 |
# Search PyPI, the Python Package Index, and retrieve latest mechanize
|
| 4 |
# tarball.
|
| 5 |
|
| 6 |
# This is just to demonstrate mechanize: You should use EasyInstall to
|
| 7 |
# do this, not this silly script.
|
| 8 |
|
| 9 |
import sys, os, re
|
| 10 |
|
| 11 |
import mechanize
|
| 12 |
|
| 13 |
b = mechanize.Browser(
|
| 14 |
# mechanize's XHTML support needs work, so is currently switched off. If
|
| 15 |
# we want to get our work done, we have to turn it on by supplying a
|
| 16 |
# mechanize.Factory (with XHTML support turned on):
|
| 17 |
factory=mechanize.DefaultFactory(i_want_broken_xhtml_support=True)
|
| 18 |
)
|
| 19 |
|
| 20 |
# search PyPI
|
| 21 |
b.open("http://www.python.org/pypi")
|
| 22 |
b.follow_link(text="Search", nr=1)
|
| 23 |
b.select_form(nr=0)
|
| 24 |
b["name"] = "mechanize"
|
| 25 |
b.submit()
|
| 26 |
|
| 27 |
# 2005-05-20 no longer necessary, only one version there, so PyPI takes
|
| 28 |
# us direct to PKG-INFO page
|
| 29 |
## # find latest release
|
| 30 |
## VERSION_RE = re.compile(r"(?P<major>\d+)\.(?P<minor>\d+)\.(?P<bugfix>\d+)"
|
| 31 |
## r"(?P<state>[ab])?(?:-pre)?(?P<pre>\d+)?$")
|
| 32 |
## def parse_version(text):
|
| 33 |
## m = VERSION_RE.match(text)
|
| 34 |
## if m is None:
|
| 35 |
## raise ValueError
|
| 36 |
## return tuple([m.groupdict()[part] for part in
|
| 37 |
## ("major", "minor", "bugfix", "state", "pre")])
|
| 38 |
## MECHANIZE_RE = re.compile(r"mechanize-?(.*)")
|
| 39 |
## links = b.links(text_regex=MECHANIZE_RE)
|
| 40 |
## versions = []
|
| 41 |
## for link in links:
|
| 42 |
## m = MECHANIZE_RE.search(link.text)
|
| 43 |
## version_string = m.group(1).strip(' \t\xa0')
|
| 44 |
## tup = parse_version(version_string)[:3]
|
| 45 |
## versions.append(tup)
|
| 46 |
## latest = links[versions.index(max(versions))]
|
| 47 |
|
| 48 |
# get tarball
|
| 49 |
## b.follow_link(latest) # to PKG-INFO page
|
| 50 |
r = b.follow_link(text_regex=re.compile(r"\.tar\.gz"))
|
| 51 |
filename = os.path.basename(b.geturl())
|
| 52 |
if os.path.exists(filename):
|
| 53 |
sys.exit("%s already exists, not grabbing" % filename)
|
| 54 |
f = file(filename, "wb")
|
| 55 |
while 1:
|
| 56 |
data = r.read(1024)
|
| 57 |
if not data: break
|
| 58 |
f.write(data)
|
| 59 |
f.close()
|