Search code examples
pythonmechanizemechanize-python

How to fill and submit a form using python


I am filling a form of a web page with the help of mechanize module but I am getting error when I run my code. I just want to fill the form and submit it successfully.

My attempt :

code snippet from this stack answer

import re
from mechanize import Browser

username="Bob"
password="admin"
br = Browser()

# Ignore robots.txt
br.set_handle_robots( False )
# Google demands a user-agent that isn't a robot
br.addheaders = [('User-agent', 'Firefox')]

br.open("https://fb.vivoliker.com/app/fb/token")
br.select_form(name="order")
br["u"] = [username]  
br["p"]=[password]

response = br.submit()  

Output : Error (FormNotFoundError)

but what should I enter the name in br.select_form() because when I see source code of web page their is no name attribute set to that form.

Html source code of form from web page

<div class="container">
<form ls-form="fb-init">
<input type="hidden" name="machine_id">
<div class="form-group row">
<input id="u" type="text" class="form-control" placeholder="Facebook Username / Id / Email / Mobile Number" required="required">
</div>
<div class="form-group row">
<input id="p" type="password" class="form-control" placeholder="Facebook Password" required="required">
</div>
<div class="form-group row mt-3">
<button type="button" id='generating' class="btn btn-primary btn-block" onclick="if (!window.__cfRLUnblockHandlers) return false; get()" data-cf-modified-4e9e40fa9e78b45594c87eaa-="">Get Access Token</button>
</div>
<div ls-form="event"></div>
</form>

Expected output : My form should be submit with the values that I given. see javascript of this webpage given below . I want to fill and submit form of this web page : Web page source


Solution

  • I believe the form you want to select is ls-form=fb-init

    However, since mechanize module requires replacing hyphens with underscores to convert HTML attrs to keyword arguments, you would want to write it like this:

    br.select_form(ls_form='fb-init')
    

    To clarify, the correct form to select is not named 'order', the form is named 'fb-init' and it is a ls-form (written as 'ls_form' with underscore). So with the change, it should be like this:

    import re
    from mechanize import Browser
    
    username="Bob"
    password="admin"
    br = Browser()
    
    # Ignore robots.txt
    br.set_handle_robots( False )
    # Google demands a user-agent that isn't a robot
    br.addheaders = [('User-agent', 'Firefox')]
    
    br.open("https://fb.vivoliker.com/app/fb/token")
    br.select_form(ls_form='fb-init')
    

    And then continue from there.