Skip to content

July 9, 2010

2

Example of using Python to logon & access Ajax (JSON) webpage in the background

by Joe Kuan

We have an application written in PyGtk. Recently, we need to modify the application to access one of our AJAX/JSON webpages in the background. The beauty of AJAX/JSON webpages opens a channel for any applications to easily access the content. Especially for LAMP product, this avoids directly connecting to the database and using specific SQL queries. As long as the webpages are constructed in AJAX/JSON, then the Python cjson or json package can parse the returned JSON result into a dictionary object.

On a AJAX login webpage, when a user enters username & password and clicks login button, the Javascript calls the login action script, returns the result in JSON and stores the cookie. As in Python, we only need to access the login action script. Here is a modified example:

import cjson
import urllib
import urllib2
import cookielib

URL = "https://%s%s" % (SITE, LOGIN_PAGE)
params = urllib.urlencode({ 'Username' : username, 'Password' : password })
headers = {"Content-type": "application/x-www-form-urlencoded"}
request = urllib2.Request(URL, params, headers)
cookies = cookielib.CookieJar()
ck_opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
try:
    response = ck_opener.open(request)
    rspTxt = response.read()
    rslt = cjson.decode(rspTxt)
except:
    print "Failed open URL\n"
    return

if (rslt['Result'] == 'SUCCESS'):
    print "Login successfully\n"
else:
    print "Login failed\n"

To download a file from a webpage and store it locally

params = urllib.urlencode({ 'file' : filename })
URL = "https://%s%s?%s" % (SITE, DOWNLOAD_PAGE, params)
request = urllib2.Request(URL)
try:
    response = url_opener.open(URL)
except:
    print "URL open error\n"
    return

local_file = open("/tmp/download_file", "w")
content = response.read()
# Do some processing on file content if requires
# .....
local_file.write(content)
local_file.close()
2 Comments Post a comment
  1. Sep 23 2014

    Good article. I absolutely love this website. Continue the good work!

    Reply

Trackbacks & Pingbacks

  1. All Around the World News

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: