#Python Version 2.5
#
#
#we need the following modules

import urllib2,string
from BeautifulSoup import BeautifulSoup


def main():
    # parameter and constants
    team_url='https://launchpad.net/~ubuntu-co/+members'

    # open team's web page
    team_page=urllib2.urlopen(team_url)

    # Use BeautifulSoup to parse html
    soup0 = BeautifulSoup(team_page)
    
    #Find active members
    p=soup0.find("table",{ "id":"activemembers"})
    
    #Convert element to string and use BeautifulSoup again
    soup1 = BeautifulSoup(str(p))
    
    #Prepare output as a table
    members_table=['<table class="listing sortable" id="activemembers"><thead><tr><th>Nombre</th><th>Ubuntero?</th><th>Karma</th></tr></thead><tbody>']
    
    #Find all the ocurrences of <a href=""> in the member's table
    member_data=soup1.findAll('a')
    
    for i in member_data:
	# get member's url
	member_url='https://launchpad.net'+str(i.get('href'))
        # Open member's web page
	member_page=urllib2.urlopen(member_url)
	# Use BeautifulSoup to parse html
	soup2=BeautifulSoup(member_page)
        #Check to see if the opened page belongs to a group, if it's not the case, get relevant data
        q=soup2.find("a",{ "class":"menu-link-members"})
	if q == None:
	        # add member data to output table
        	members_table.append('<tr><td>'+str(i).replace('href="','href="https://launchpad.net')+'</td><td>')
	        #find the word "Ubuntero" and if it says "Yes" or no, add relevant data to output table
		u=soup2.find(text='Ubuntero:')
		if u <> None:
			v=u.findNext(text=True)
			if v.find("Yes") > 0:
	   			members_table.append('Si')
			else:	 
		   		members_table.append('No')
		else:	
			members_table.append('No')
		# Find Member's karma, add it to output table
		karma=soup2.find("span",{ "id":"karma-total"}).contents[0]
		members_table.append('</td><td>'+str(karma)+'</td></tr>')
    # Add trailing info for table	
    members_table.append('</tbody></table>')
    # Convert element to string
    doc= ''.join(members_table)
    # Use BeautifulSoup to parse html
    soup = BeautifulSoup(doc)
    # Print output table
    print soup.prettify()
      
#call main function
main() 

