twisted-webclient将网页另存为文件
from twisted.web import clientimport tempfiledef downloadToTempFile(url): """ Given a URL, returns a Deferred that will be called back with the name of a temporary file containing the downloaded data. """ tmpfd, tempfilename = tempfile.mkstemp( ) os.close(tmpfd) return client.downloadPage(url, tempfilename).addCallback( returnFilename, tempfilename)def returnFilename(result, filename): return filenameif __name__ == "_ _main_ _": import sys, os from twisted.internet import reactor def printFile(filename): for line in file(filename, 'r+b'): sys.stdout.write(line) os.unlink(filename) # delete file once we're done with it reactor.stop( ) def printError(failure): print >> sys.stderr, "Error:", failure.getErrorMessage( ) reactor.stop( ) if len(sys.argv) == 3: url = sys.argv[2] downloadToTempFile(url).addCallback( printFile).addErrback( printError) reactor.run( ) else: print "Usage: %s <URL>" % sys.argv[0]
?