Skip to content

Instantly share code, notes, and snippets.

@mansilla
Created August 10, 2015 14:36
Show Gist options
  • Select an option

  • Save mansilla/ddb9f60c767ade7bb528 to your computer and use it in GitHub Desktop.

Select an option

Save mansilla/ddb9f60c767ade7bb528 to your computer and use it in GitHub Desktop.

Revisions

  1. mansilla created this gist Aug 10, 2015.
    47 changes: 47 additions & 0 deletions using-mechanize.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    page = br.open("http://example.com")

    # page tiene el resultado de la request
    html_source_code = page.read() # br esta ahora en example.com

    #=== Interactuando con los formularios
    br.select_form(name="form-name") # si la forma tiene name
    # si no tiene el tag "name", hay que buscar la forma por su
    # indice en el codigo de la pagina
    br.form = list(br.forms())[0]
    # una vez seleccionado el formulario podemos llenarlo
    br.form["login"]=login
    br.form["passw"]=password
    # tambien podemos ver los controles de una forma
    for control in br.form.controls:
    print control
    print "type=%s, name=%s value=%s" % \
    (control.type, control.name, br[control.name])
    # o de esta otra manera
    control = br.form.find_control("controlname")
    if control.type == "select": # tiene un control de selecccion
    for item in control.items:
    print " name=%s values=%s" % \
    (item.name, str([label.text for label in item.get_labels()]))
    br.form[control.name] = ["ItemName"]
    # -- o si es otro tipo de control
    if control.type == "text": # es un control de texto
    control.value = "stuff here"
    # equivalentemente
    br.form["controlname"] = "stuff here"
    # -- radio control
    br.form[ 'radio-name' ] = [ '2' ]

    # finalmente hacemos el submit
    br.sumbit()
    #=== Buscando elementos en la pagina
    for link in br.links():
    print link.text, link.url

    request = br.click_link(link) # objeto request como resultado
    response = br.follow_link(link) # response como resultado
    print response.geturl()
    print response.read()

    # en cualquier caso si hacemos
    resp = br.open('https://newexample.html')
    # el objeto br se encargara de gestionar las cookies