892 lines · 29.1 KB · Python
RawDownload
#! /usr/bin/env python # Original code by Guido van Rossum; extensive changes by Sam Bayer,# including code to check URL fragments. """Web tree checker. This utility is handy to check a subweb of the world-wide web forerrors.  A subweb is specified by giving one or more ``root URLs''; apage belongs to the subweb if one of the root URLs is an initialprefix of it. File URL extension: In order to easy the checking of subwebs via the local file system,the interpretation of ``file:'' URLs is extended to mimic the behaviorof your average HTTP daemon: if a directory pathname is given, thefile index.html in that directory is returned if it exists, otherwisea directory listing is returned.  Now, you can point webchecker to thedocument tree in the local file system of your HTTP daemon, and havemost of it checked.  In fact the default works this way if your localweb tree is located at /usr/local/etc/httpd/htdpcs (the default forthe NCSA HTTP daemon and probably others). Report printed: When done, it reports pages with bad links within the subweb.  Wheninterrupted, it reports for the pages that it has checked already. In verbose mode, additional messages are printed during theinformation gathering phase.  By default, it prints a summary of itswork status every 50 URLs (adjustable with the -r option), and itreports errors as they are encountered.  Use the -q option to disablethis output. Checkpoint feature: Whether interrupted or not, it dumps its state (a Python pickle) to acheckpoint file and the -R option allows it to restart from thecheckpoint (assuming that the pages on the subweb that were alreadyprocessed haven't changed).  Even when it has run till completion, -Rcan still be useful -- it will print the reports again, and -Rq printsthe errors only.  In this case, the checkpoint file is not writtenagain.  The checkpoint file can be set with the -d option. The checkpoint file is written as a Python pickle.  Remember thatPython's pickle module is currently quite slow.  Give it the time itneeds to load and save the checkpoint file.  When interrupted whilewriting the checkpoint file, the old checkpoint file is notoverwritten, but all work done in the current run is lost. Miscellaneous: - You may find the (Tk-based) GUI version easier to use.  See wcgui.py. - Webchecker honors the "robots.txt" convention.  Thanks to SkipMontanaro for his robotparser.py module (included in this directory)!The agent name is hardwired to "webchecker".  URLs that are disallowedby the robots.txt file are reported as external URLs. - Because the SGML parser is a bit slow, very large SGML files areskipped.  The size limit can be set with the -m option. - When the server or protocol does not tell us a file's type, we guessit based on the URL's suffix.  The mimetypes.py module (also in thisdirectory) has a built-in table mapping most currently known suffixes,and in addition attempts to read the mime.types configuration files inthe default locations of Netscape and the NCSA HTTP daemon. - We follow links indicated by <A>, <FRAME> and <IMG> tags.  We alsohonor the <BASE> tag. - We now check internal NAME anchor links, as well as toplevel links. - Checking external links is now done by default; use -x to *disable*this feature.  External links are now checked during normalprocessing.  (XXX The status of a checked link could be categorizedbetter.  Later...) - If external links are not checked, you can use the -t flag toprovide specific overrides to -x. Usage: webchecker.py [option] ... [rooturl] ... Options: -R        -- restart from checkpoint file-d file   -- checkpoint filename (default %(DUMPFILE)s)-m bytes  -- skip HTML pages larger than this size (default %(MAXPAGE)d)-n        -- reports only, no checking (use with -R)-q        -- quiet operation (also suppresses external links report)-r number -- number of links processed per round (default %(ROUNDSIZE)d)-t root   -- specify root dir which should be treated as internal (can repeat)-v        -- verbose operation; repeating -v will increase verbosity-x        -- don't check external links (these are often slow to check)-a        -- don't check name anchors Arguments: rooturl   -- URL to start checking             (default %(DEFROOT)s) """  __version__ = "$Revision: 50851 $"  import sysimport osfrom types import *import StringIOimport getoptimport pickle import urllibimport urlparseimport sgmllibimport cgi import mimetypesimport robotparser # Extract real version number if necessaryif __version__[0] == '$':    _v = __version__.split()    if len(_v) == 3:        __version__ = _v[1]  # Tunable parametersDEFROOT = "file:/usr/local/etc/httpd/htdocs/"   # Default root URLCHECKEXT = 1                            # Check external references (1 deep)VERBOSE = 1                             # Verbosity level (0-3)MAXPAGE = 150000                        # Ignore files bigger than thisROUNDSIZE = 50                          # Number of links processed per roundDUMPFILE = "@webchecker.pickle"         # Pickled checkpointAGENTNAME = "webchecker"                # Agent name for robots.txt parserNONAMES = 0                             # Force name anchor checking  # Global variables  def main():    checkext = CHECKEXT    verbose = VERBOSE    maxpage = MAXPAGE    roundsize = ROUNDSIZE    dumpfile = DUMPFILE    restart = 0    norun = 0     try:        opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')    except getopt.error, msg:        sys.stdout = sys.stderr        print msg        print __doc__%globals()        sys.exit(2)     # The extra_roots variable collects extra roots.    extra_roots = []    nonames = NONAMES     for o, a in opts:        if o == '-R':            restart = 1        if o == '-d':            dumpfile = a        if o == '-m':            maxpage = int(a)        if o == '-n':            norun = 1        if o == '-q':            verbose = 0        if o == '-r':            roundsize = int(a)        if o == '-t':            extra_roots.append(a)        if o == '-a':            nonames = not nonames        if o == '-v':            verbose = verbose + 1        if o == '-x':            checkext = not checkext     if verbose > 0:        print AGENTNAME, "version", __version__     if restart:        c = load_pickle(dumpfile=dumpfile, verbose=verbose)    else:        c = Checker()     c.setflags(checkext=checkext, verbose=verbose,               maxpage=maxpage, roundsize=roundsize,               nonames=nonames               )     if not restart and not args:        args.append(DEFROOT)     for arg in args:        c.addroot(arg)     # The -t flag is only needed if external links are not to be    # checked. So -t values are ignored unless -x was specified.    if not checkext:        for root in extra_roots:            # Make sure it's terminated by a slash,            # so that addroot doesn't discard the last            # directory component.            if root[-1] != "/":                root = root + "/"            c.addroot(root, add_to_do = 0)     try:         if not norun:            try:                c.run()            except KeyboardInterrupt:                if verbose > 0:                    print "[run interrupted]"         try:            c.report()        except KeyboardInterrupt:            if verbose > 0:                print "[report interrupted]"     finally:        if c.save_pickle(dumpfile):            if dumpfile == DUMPFILE:                print "Use ``%s -R'' to restart." % sys.argv[0]            else:                print "Use ``%s -R -d %s'' to restart." % (sys.argv[0],                                                           dumpfile)  def load_pickle(dumpfile=DUMPFILE, verbose=VERBOSE):    if verbose > 0:        print "Loading checkpoint from %s ..." % dumpfile    f = open(dumpfile, "rb")    c = pickle.load(f)    f.close()    if verbose > 0:        print "Done."        print "Root:", "\n      ".join(c.roots)    return c  class Checker:     checkext = CHECKEXT    verbose = VERBOSE    maxpage = MAXPAGE    roundsize = ROUNDSIZE    nonames = NONAMES     validflags = tuple(dir())     def __init__(self):        self.reset()     def setflags(self, **kw):        for key in kw.keys():            if key not in self.validflags:                raise NameError, "invalid keyword argument: %s" % str(key)        for key, value in kw.items():            setattr(self, key, value)     def reset(self):        self.roots = []        self.todo = {}        self.done = {}        self.bad = {}         # Add a name table, so that the name URLs can be checked. Also        # serves as an implicit cache for which URLs are done.        self.name_table = {}         self.round = 0        # The following are not pickled:        self.robots = {}        self.errors = {}        self.urlopener = MyURLopener()        self.changed = 0     def note(self, level, format, *args):        if self.verbose > level:            if args:                format = format%args            self.message(format)     def message(self, format, *args):        if args:            format = format%args        print format     def __getstate__(self):        return (self.roots, self.todo, self.done, self.bad, self.round)     def __setstate__(self, state):        self.reset()        (self.roots, self.todo, self.done, self.bad, self.round) = state        for root in self.roots:            self.addrobot(root)        for url in self.bad.keys():            self.markerror(url)     def addroot(self, root, add_to_do = 1):        if root not in self.roots:            troot = root            scheme, netloc, path, params, query, fragment = \                    urlparse.urlparse(root)            i = path.rfind("/") + 1            if 0 < i < len(path):                path = path[:i]                troot = urlparse.urlunparse((scheme, netloc, path,                                             params, query, fragment))            self.roots.append(troot)            self.addrobot(root)            if add_to_do:                self.newlink((root, ""), ("<root>", root))     def addrobot(self, root):        root = urlparse.urljoin(root, "/")        if self.robots.has_key(root): return        url = urlparse.urljoin(root, "/robots.txt")        self.robots[root] = rp = robotparser.RobotFileParser()        self.note(2, "Parsing %s", url)        rp.debug = self.verbose > 3        rp.set_url(url)        try:            rp.read()        except (OSError, IOError), msg:            self.note(1, "I/O error parsing %s: %s", url, msg)     def run(self):        while self.todo:            self.round = self.round + 1            self.note(0, "\nRound %d (%s)\n", self.round, self.status())            urls = self.todo.keys()            urls.sort()            del urls[self.roundsize:]            for url in urls:                self.dopage(url)     def status(self):        return "%d total, %d to do, %d done, %d bad" % (            len(self.todo)+len(self.done),            len(self.todo), len(self.done),            len(self.bad))     def report(self):        self.message("")        if not self.todo: s = "Final"        else: s = "Interim"        self.message("%s Report (%s)", s, self.status())        self.report_errors()     def report_errors(self):        if not self.bad:            self.message("\nNo errors")            return        self.message("\nError Report:")        sources = self.errors.keys()        sources.sort()        for source in sources:            triples = self.errors[source]            self.message("")            if len(triples) > 1:                self.message("%d Errors in %s", len(triples), source)            else:                self.message("Error in %s", source)            # Call self.format_url() instead of referring            # to the URL directly, since the URLs in these            # triples is now a (URL, fragment) pair. The value            # of the "source" variable comes from the list of            # origins, and is a URL, not a pair.            for url, rawlink, msg in triples:                if rawlink != self.format_url(url): s = " (%s)" % rawlink                else: s = ""                self.message("  HREF %s%s\n    msg %s",                             self.format_url(url), s, msg)     def dopage(self, url_pair):         # All printing of URLs uses format_url(); argument changed to        # url_pair for clarity.        if self.verbose > 1:            if self.verbose > 2:                self.show("Check ", self.format_url(url_pair),                          "  from", self.todo[url_pair])            else:                self.message("Check %s", self.format_url(url_pair))        url, local_fragment = url_pair        if local_fragment and self.nonames:            self.markdone(url_pair)            return        try:            page = self.getpage(url_pair)        except sgmllib.SGMLParseError, msg:            msg = self.sanitize(msg)            self.note(0, "Error parsing %s: %s",                          self.format_url(url_pair), msg)            # Dont actually mark the URL as bad - it exists, just            # we can't parse it!            page = None        if page:            # Store the page which corresponds to this URL.            self.name_table[url] = page            # If there is a fragment in this url_pair, and it's not            # in the list of names for the page, call setbad(), since            # it's a missing anchor.            if local_fragment and local_fragment not in page.getnames():                self.setbad(url_pair, ("Missing name anchor `%s'" % local_fragment))            for info in page.getlinkinfos():                # getlinkinfos() now returns the fragment as well,                # and we store that fragment here in the "todo" dictionary.                link, rawlink, fragment = info                # However, we don't want the fragment as the origin, since                # the origin is logically a page.                origin = url, rawlink                self.newlink((link, fragment), origin)        else:            # If no page has been created yet, we want to            # record that fact.            self.name_table[url_pair[0]] = None        self.markdone(url_pair)     def newlink(self, url, origin):        if self.done.has_key(url):            self.newdonelink(url, origin)        else:            self.newtodolink(url, origin)     def newdonelink(self, url, origin):        if origin not in self.done[url]:            self.done[url].append(origin)         # Call self.format_url(), since the URL here        # is now a (URL, fragment) pair.        self.note(3, "  Done link %s", self.format_url(url))         # Make sure that if it's bad, that the origin gets added.        if self.bad.has_key(url):            source, rawlink = origin            triple = url, rawlink, self.bad[url]            self.seterror(source, triple)     def newtodolink(self, url, origin):        # Call self.format_url(), since the URL here        # is now a (URL, fragment) pair.        if self.todo.has_key(url):            if origin not in self.todo[url]:                self.todo[url].append(origin)            self.note(3, "  Seen todo link %s", self.format_url(url))        else:            self.todo[url] = [origin]            self.note(3, "  New todo link %s", self.format_url(url))     def format_url(self, url):        link, fragment = url        if fragment: return link + "#" + fragment        else: return link     def markdone(self, url):        self.done[url] = self.todo[url]        del self.todo[url]        self.changed = 1     def inroots(self, url):        for root in self.roots:            if url[:len(root)] == root:                return self.isallowed(root, url)        return 0     def isallowed(self, root, url):        root = urlparse.urljoin(root, "/")        return self.robots[root].can_fetch(AGENTNAME, url)     def getpage(self, url_pair):        # Incoming argument name is a (URL, fragment) pair.        # The page may have been cached in the name_table variable.        url, fragment = url_pair        if self.name_table.has_key(url):            return self.name_table[url]         scheme, path = urllib.splittype(url)        if scheme in ('mailto', 'news', 'javascript', 'telnet'):            self.note(1, " Not checking %s URL" % scheme)            return None        isint = self.inroots(url)         # Ensure that openpage gets the URL pair to        # print out its error message and record the error pair        # correctly.

Lines 1–500 of 892.