How to Fill out Text Boxes and Submit Forms using the Selenium Module in Python



Python


In this article, we show how to fill out text boxes and submit forms using the Selenium module in Python.

So the selenium module in Python is a very dynamic and useful module when working with web browsers such as Firefox or Chrome.

Using the selenium module, we can open up a browser, go to any URL we need to go to, and even do things such as fill out forms and submit.

For example, you can write custom Python code that will go direct to a website such as Facebook and log you into your account.

The example code we will do on this page opens up the Firefox web browser, goes to Facebook's home page, and logs you in into your account.

In order to run the program on this page, you will need to install the selenium module, which you can do with the line, pip install selenium. You also will need to install either the geckodriver (if you are working with the Firefox web browser) or the ChromeDriver (if you are working with the Chrome web browser).

So in order to select a text box in order to write text to it, the first thing we have to do is find a way to identify the text box.

So when you go to facebook's home page, there are 2 text boxes: Email or Phone number and Password.

Normally the best way to target an HTML element is through the id element.

So when we go to facebook's home page and select 'View Page Source', we find out that the id for the email or phone number text box is 'ap-email'. The id for the password text box is 'pass'.

Using this information, we can enter text into the text boxes and then submit any form such as user login.



So the first thing we have to do is import webdriver from the selenium module.

We use Firefox in this case, so we set the variable, browser, equal to, webdriver.Firefox()

We then use the get() function to retrieve the home page of facebook.

We then create a variable, email, which we set to, browser.find_element_by_id('email')

This locates the email text box on the facebook home page using the id attribute.

We then can enter text into this email text box by using the send_keys() function, which is how you write to a text box using the selenium module.

We then create another variable, password, which we set to, browser.find_element_by_id('pass')

This locates the password text box on the facebook home page, again using the id attribute.

We then submit the login, complete the login process, by using the submit() function.

The submit() function submits the form, which, in this case, logs us into the facebook account.

And this is how we can fill out text boxes and submit forms using the Selenium module in Python.


Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...