Skip to content

Instantly share code, notes, and snippets.

@youpy
Created February 25, 2010 15:36
Show Gist options
  • Save youpy/314640 to your computer and use it in GitHub Desktop.
Save youpy/314640 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
__version__ = "0.00001"
import sys
import optparse
try:
import Foundation
import WebKit
import AppKit
import objc
import os
except ImportError:
print "Cannot find pyobjc library files. Are you sure it is installed?"
sys.exit()
class AppDelegate (Foundation.NSObject):
# what happens when the app starts up
def applicationDidFinishLaunching_(self, aNotification):
webview = aNotification.object().windows()[0].contentView()
webview.frameLoadDelegate().getURL(webview)
self.performSelector_withObject_afterDelay_( "timeout:", None, 60 )
def timeout_(self, obj):
NSLog("timed out!")
NSApplication.sharedApplication().terminate_(None)
class WebkitLoad (Foundation.NSObject, WebKit.protocols.WebFrameLoadDelegate):
# what happens if something goes wrong while loading
def webView_didFailLoadWithError_forFrame_(self,webview,error,frame):
print " ... something went wrong: "+error.localizedDescription()
self.terminate()
def webView_didFailProvisionalLoadWithError_forFrame_(self,webview,error,frame):
print " ... something went wrong: "+error.localizedDescription()
self.terminate()
def getURL(self,webview):
if self.url:
url = self.url
else:
self.terminate()
print "Fetching", url, "..."
webview.mainFrame().loadRequest_(Foundation.NSURLRequest.requestWithURL_(Foundation.NSURL.URLWithString_(url)))
if not webview.mainFrame().provisionalDataSource():
print " ... not a proper url?"
# what happens when the page has finished loading
def webView_didFinishLoadForFrame_(self,webview,frame):
# don't care about subframes
if (frame == webview.mainFrame()):
Foundation.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( self.options.delay, self, self.doEval, webview, False)
def doEval(self,timer):
webview = timer.userInfo()
wso = webview.windowScriptObject();
result = wso.evaluateWebScript_("(function() { %s })()" % self.script);
if(type(result) != WebKit.WebUndefined):
print result
print " ... done"
self.terminate()
def terminate(self):
AppKit.NSApplication.sharedApplication().terminate_(None)
def main():
# parse the command line
usage = """%prog [options] 'return document.documentElement.outerHTML' http://example.net/
examples:
%prog -h | less # full documentation"""
cmdparser = optparse.OptionParser(usage,version=(" ".join([os.path.basename(__file__), __version__])))
cmdparser.add_option("--debug", action="store_true",
help=optparse.SUPPRESS_HELP)
cmdparser.add_option("--delay",type="float",default=0,
help="delay between page load finishing and eval")
(options, args) = cmdparser.parse_args()
app = AppKit.NSApplication.sharedApplication()
# create an app delegate
delegate = AppDelegate.alloc().init()
AppKit.NSApp().setDelegate_(delegate)
# create a window
rect = Foundation.NSMakeRect(0,0,100,100)
win = AppKit.NSWindow.alloc()
win.initWithContentRect_styleMask_backing_defer_ (rect,
AppKit.NSBorderlessWindowMask, 2, 0)
if options.debug:
win.orderFrontRegardless()
# create a webview object
webview = WebKit.WebView.alloc()
webview.initWithFrame_(rect)
# turn off scrolling so the content is actually x wide and not x-15
webview.mainFrame().frameView().setAllowsScrolling_(objc.NO)
webview.setPreferencesIdentifier_(os.path.basename(__file__))
# add the webview to the window
win.setContentView_(webview)
# create a LoadDelegate
loaddelegate = WebkitLoad.alloc().init()
loaddelegate.options = options
loaddelegate.script = args.pop(0)
loaddelegate.url = args.pop(0)
webview.setFrameLoadDelegate_(loaddelegate)
app.run()
if __name__ == '__main__' : main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment