tags:

views:

127

answers:

4

Hi, The below code extracts the branch number and the test environment to deploy that particular branches build on from a txt file (branch_dest.txt). Then it parses HTML pages to reach a webpage which contains some checkboxes. I want to check the "Select/Deselect All" checkbox and then click the "Deploy" button on that webpage.

How do i code this? I am basically from QA(Tester). So please help.

URL = "http://11.12.13.27:8080/cruisecontrol"

from urllib2 import urlopen
from HTMLParser import HTMLParser

import re

# Fetching links using HTMLParser
def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(url).read())
    parser.close()
    return parser.links

# Build url for Deploy page
def get_deploy_url():
    url = URL + "/buildresults/xxx_%s_nightly_build" % branch
    print url
    for link in get_links(url):
        if link["href"].startswith("Deploy"):
            return "%s/%s" % (URL, link["href"])
        print link["href"]

# Build url for Destination page
def get_destination_url():
    url = get_deploy_url()
    print url
    destination_re = re.compile(r"%s" % destination)
    for link in get_links(url):
        if destination_re.search(link["href"]):
            return "http://11.12.13.27:8080/cruisecontrol/" + link["href"]

# Parsing HTML pages 
class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwd):
        HTMLParser.__init__(self, *args, **kwd)
        self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                self.links.append(dict(attrs))

    def handle_endtag(self, tag):
        pass

if __name__ == "__main__":
    # Read the branch name and the test destination to deploy on
    lines = [x.split(':') for x in open("branch_dest.txt")]
    print lines
    branch = "%s" % lines[0][1].strip()
    print branch
    destination = "%s" % lines[1][1].strip()
    print destination

    final_url = get_destination_url()
    if final_url is None:
        print "Could not find a destination to deploy"
    else:
        print final_url

HTML of the webpage

<html>
<head>
    <title>Deploy Build</title> 
    <link type="text/css" rel="stylesheet" href="css/cruisecontrol.css"/>
    <style type="text/css">
        td.pad {
            padding: 2 5
        }

        .odd-row {
            background-color: white;
        }

        .even-row {
            background-color: #FFFFCC;
        }

        .header-row {
            background-color: white;
            color: darkblue;
        }
    </style>
    <script type="text/javascript">
        function setCheckboxes(checked)
        {
            var elements = document.getElementsByTagName('input');
            for( var i=0; i < elements.length; i++ )
            {
                if ( elements[i].type == 'checkbox' )
                {
                    elements[i].checked = checked;
                }
            }
        }
    </script>

</head>

<body background="images/bluebg.gif">
    <h1 class="white" align="center">Select which clients to build</h1>

    <form name="cfg" action="DeployStart.jsp" method="POST">
        <input type="hidden" name="name" value="Test 4" />
        <input type="hidden" name="scriptPath" value="f:/Projects/PokerDeployer" />
        <input type="hidden" name="script" value="test4.cfg" />
        <input type="hidden" name="artifacts" value="f:/cruisecontrol/s_drive/artifacts/Poker-TTM_trunk_nightly_build/20100512230443" />
        <input type="hidden" name="configPath" value="f:/Projects/Poker-TTM_trunk_nightly_build/source/tools/PokerDeployer" />

    <table align="center" border="0" cellpadding="0" cellspacing="0" width="20%">
        <tr>
            <td bgcolor="#FFFFFF"><img border="0" src="images/bluestripestop.gif"/></td>
            <td bgcolor="#FFFFFF" align="right"><img border="0" src="images/bluestripestopright.gif"/></td>
        </tr>
        <tr>
            <td bgcolor="#DDDDDD" colspan="2" align="left" class="pad">
                <input type="checkbox" name="all_top" onClick="setCheckboxes(this.checked)"/> Select / deselect all<br>
            </td>
        </tr>



        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code" checked /> POK_code<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.SVS_code" checked /> SVS_code<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.PAT_code" /> PAT_code<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_gms" checked /> POK_code_gms<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_gms_cpn" checked /> POK_code_gms_cpn<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_mini" /> POK_code_mini<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.LTM_code" checked /> LTM_code<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.LTM_tot_code" /> LTM_tot_code<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_paradise" /> POK_code_paradise<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_forfun" /> POK_code_forfun<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_pokerheaven" /> POK_code_pokerheaven<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_totalpoker" /> POK_code_totalpoker<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_las" /> POK_code_las<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_italian" /> POK_code_italian<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_bulgarian" /> POK_code_bulgarian<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_finnish" /> POK_code_finnish<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_danish" /> POK_code_danish<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_french" /> POK_code_french<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_greek" /> POK_code_greek<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_german" /> POK_code_german<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_croatian" /> POK_code_croatian<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_polish" /> POK_code_polish<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_portuguese" /> POK_code_portuguese<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_romanian" /> POK_code_romanian<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_russian" /> POK_code_russian<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_slovak" /> POK_code_slovak<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_spanish" /> POK_code_spanish<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_czech" /> POK_code_czech<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_swedish" /> POK_code_swedish<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_hungarian" /> POK_code_hungarian<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_turkish" /> POK_code_turkish<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_albanian" /> POK_code_albanian<br>

            </td>
        </tr>


        <tr class="odd-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_austrian" /> POK_code_austrian<br>

            </td>
        </tr>


        <tr class="even-row ">
            <td colspan="2" align="left" class="pad">

                <input type="checkbox" name="client.POK_code_brazilian" /> POK_code_brazilian<br>

            </td>
        </tr>

        <tr>
            <td bgcolor="#DDDDDD" colspan="2" align="left" class="pad">
                <input type="checkbox" name="all" onClick="setCheckboxes(this.checked)"/> Select / deselect all<br>
            </td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF" colspan="2" align="center" class="pad">
                <input type="submit" value="Deploy" />
            </td>
        </tr>
        <tr>
            <td bgcolor="#FFFFFF"><img border="0" src="images/bluestripesbottom.gif"/></td>
            <td align="right" bgcolor="#FFFFFF"><img border="0" src="images/bluestripesbottomright.gif"/></td>
        </tr>
    </table>

    </form>
</body>
</html>
+1  A: 

Have you tried the mechanize module? It was made just for this purpose.

Eli Bendersky
Please let me know how to where to install mechanize
see instructions here: http://wwwsearch.sourceforge.net/mechanize/download.html - after downloading and unzipping you must run `python setup.py install` in the unzipped mechanize directory
Eli Bendersky
A: 

You can use urllib to send HTTP POST requests.

import urllib
params = urllib.urlencode({
    'name': 'Test 4',
    'scriptPath': '...',
    'script': 'test4.cfg',
    'artifacts': '...',
    'configPath': '...',
    'client.POK_code': '1'
    # Include the additional arguments of the input fields
    # i.e. all checkboxes
})
f = urllib.urlopen('http://url/to/DeployStart.jsp', params)
print f.read()
ThiefMaster
If u see the code, i would not know these parameters as i get the branch name and the test environment to deploy the build on from a txt file. I had just cpy pasted the html of the webpage for a particular branch and a particular environment
+1  A: 

i downloaded mechanize zip file for the page that u posted and wrote the below code

import re
import mechanize, urllib1, urllib2

br = mechanize.Browser()
br.open("http://10.47.42.27:8080/cruisecontrol/DeployConfig.jsp?name=Test%204&amp;scriptPath=f:/Projects/PokerDeployer&amp;script=test4.cfg&amp;artifacts=f:/cruisecontrol/s_drive/artifacts/Poker-TTM_trunk_nightly_build/20100512230443&amp;configPath=f:/Projects/Poker-TTM_trunk_nightly_build/source/tools/PokerDeployer")
assert br.viewing_html()
print br.title()
print response1.geturl()
print response1.read()

br.select_form(name = "cfg")
response2 = br.submit()

print br.form

But it says ImportError: No module named mechanize

see instructions here: http://wwwsearch.sourceforge.net/mechanize/download.html - after downloading and unzipping you must run `python setup.py install` in the unzipped mechanize directory
Eli Bendersky
A: 

Hi, Finally managed to use ClientForms It works fine when i passed a static url But when i integrated the code with another code (which uses HTMLParser to parse webpages for the final url i.e the webpage which has the checkboxes and the submit button) i am getting HTTP version error 505.

Below is the code

URL = "http://10.47.42.27:8080/cruisecontrol"

#from urllib2 import urlopen
from HTMLParser import HTMLParser

import re
import ClientForm
import urllib2

# Fetching links using HTMLParser
def get_links(url):
    parser = MyHTMLParser()
    parser.feed(urlopen(url).read())
    parser.close()
    return parser.links

# Build url for Deploy page
def get_deploy_url():
    url = URL + "/buildresults/Poker-TTM_%s_nightly_build" % branch
    print url
    for link in get_links(url):
        if link["href"].startswith("Deploy"):
            return "%s/%s" % (URL, link["href"])

# Build url for Destination page
def get_destination_url():
    url = get_deploy_url()
    print url
    destination_re = re.compile(r"%s" % destination)
    for link in get_links(url):
        if destination_re.search(link["href"]):
            return "http://10.47.42.27:8080/cruisecontrol/" + link["href"]
        print link["href"]

# Parsing HTML pages 
class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwd):
        HTMLParser.__init__(self, *args, **kwd)
        self.links = []

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            attrs = dict(attrs)
            if "href" in attrs:
                self.links.append(dict(attrs))

    def handle_endtag(self, tag):
        pass

if __name__ == "__main__":
    # Read the branch name and the test destination to deploy on
    lines = [x.split(':') for x in open("branch_dest.txt")]
    print lines
    branch = "%s" % lines[0][1].strip()
    print branch
    destination = "%s" % lines[1][1].strip()
    print destination

    final_url = get_destination_url()
    if final_url is None:
        print "Cannot deploy here"
    else:
        print final_url
        request = urllib2.Request("%s" % final_url)
        print request
        response = urllib2.urlopen(request)
        forms = ClientForm.ParseResponse(response, backwards_compat = False)
        response.close()
        form = forms[0]
        print form
        form.find_control("all_top").items[0].selected = True
        form.find_control("client.POK_code").items[0].selected = True
        form.find_control("client.SVS_code").items[0].selected = True
        form.find_control("client.PAT_code").items[0].selected = True
        form.find_control("client.POK_code_gms").items[0].selected = True
        form.find_control("client.POK_code_gms_cpn").items[0].selected = True
        form.find_control("client.POK_code_mini").items[0].selected = True
        form.find_control("client.LTM_code").items[0].selected = True
        form.find_control("client.LTM_tot_code").items[0].selected = True
        form.find_control("client.POK_code_paradise").items[0].selected = True
        form.find_control("client.POK_code_forfun").items[0].selected = True
        form.find_control("client.POK_code_pokerheaven").items[0].selected = True
        form.find_control("client.POK_code_totalpoker").items[0].selected = True
        form.find_control("client.POK_code_las").items[0].selected = True
        form.find_control("client.POK_code_italian").items[0].selected = True
        form.find_control("client.POK_code_bulgarian").items[0].selected = True
        form.find_control("client.POK_code_finnish").items[0].selected = True
        form.find_control("client.POK_code_danish").items[0].selected = True
        form.find_control("client.POK_code_french").items[0].selected = True
        form.find_control("client.POK_code_greek").items[0].selected = True
        form.find_control("client.POK_code_german").items[0].selected = True
        form.find_control("client.POK_code_croatian").items[0].selected = True
        form.find_control("client.POK_code_polish").items[0].selected = True
        form.find_control("client.POK_code_portuguese").items[0].selected = True
        form.find_control("client.POK_code_romanian").items[0].selected = True
        form.find_control("client.POK_code_russian").items[0].selected = True
        form.find_control("client.POK_code_slovak").items[0].selected = True
        form.find_control("client.POK_code_spanish").items[0].selected = True
        form.find_control("client.POK_code_czech").items[0].selected = True
        form.find_control("client.POK_code_swedish").items[0].selected = True
        form.find_control("client.POK_code_hungarian").items[0].selected = True
        form.find_control("client.POK_code_turkish").items[0].selected = True
        form.find_control("client.POK_code_albanian").items[0].selected = True
        form.find_control("client.POK_code_austrian").items[0].selected = True
        form.find_control("client.POK_code_brazilian").items[0].selected = True
        form.find_control("all").items[0].selected = True
        print form

        ##request2 = form.click()
        try:
            response2 = urllib2.urlopen(request2)
        except urllib2.HTTPError, response2:
            pass

        print response2.geturl()
        print response2.read()
        response2.close()

Getting below error:

Traceback (most recent call last):
  File "C:\deploy_input_clientform.py", line 66, in <module>
    response = urllib2.urlopen(request)
  File "C:\Python26\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python26\lib\urllib2.py", line 397, in open
    response = meth(req, response)
  File "C:\Python26\lib\urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python26\lib\urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "C:\Python26\lib\urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 505: HTTP Version Not Supported

Please help!

Can anybody help me please!