Tuesday, August 17, 2010

Form submit using Twill


Recently, i found excellent use of Twill module of python. I have used twill before, just to check multiple login functionality of one of my plone site. That was to check load on my login script.
But, some days back, i used Twill to fetch multiple user detail from proxy site.
Here, i am just going to explain the little code, which i wrote. It might be helpful for others.

What i am doing here??

            i am opening google.com and search the term "Twill"    

Here, the first thing is, how to use twill module in python code?
download Twill from http://twill.idyll.org/

                        import twill
                        import twill.commands
                        t_com = twill.commands
                        ## get the default browser
                        t_brw = t_com.get_browser()
                        ## open the url
                        url = 'http://google.com'
                        t_brw.go(url)
                        ## get all forms from that URL
                        all_forms = t_brw.get_all_forms()         ## this returns list of form objects

                        ## now, you have to choose only that form, which is having POST method
                       
                        for each_frm in all_forms:
                            attr = each_frm.attrs             ## all attributes of form
                            if each_frm.method == 'POST':
                                ctrl = each_frm.controls    ## return all control objects within that form (all html tags as control inside form)
                                for ct in ctrl:
                                        if ct.type == 'text':     ## i did it as per my use, you can put your condition here
                                                ct._value = "twill"
                                                t_brw.clicked(each_frm,ct.attrs['name'])            ## clicked takes two parameter, form object and button name to be clicked.
                                                t_brw.submit()

                        ## you might write the output (submitted page) to any file using content = t_brw.get_html()
                        ## dont forget to reset the browser and putputs.
                        t_com.reset_browser
                        t_com.reset_output

No comments: