Search code examples
javamysqlurlgmail

Automatically Fill Username and Password Field in Web Pages using JAVA


So this is what i am trying to do, I need java to automatically open a webpage like mail.google.com and put in the username and password into respective boxes on click of a button. Now i know the code that opens up the browser and targets it to the specific url provided, i was just wondering if there was a way to tell java to fill in the username and password into respective boxes. By the way i am done with getting data from MYSQL database into string variables using JAVA...any help or suggestions??


Solution

  • Use Selenium. It's a good library where you can manipulate a web-page actions. i.e. selenium.isElementPresent("here comes the element's xpath"); will check if the element is loaded, and if it is you can use selenium.type("xpath", String/integer) in order to type in that field. Then by selenium.click("element"); you can click on an element such as submit button or something

    This, for example (without checks for present elements), should open Google.com and search for "type some random text":

    package com.example.tests;
    
    import com.thoughtworks.selenium.*;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import static org.junit.Assert.*;
    import java.util.regex.Pattern;
    
    public class Googletest {
        private Selenium selenium;
    
        @Before
        public void setUp() throws Exception {
            selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://www.google.com/");
            selenium.start();
        }
    
        @Test
        public void testGoogletest() throws Exception {
            selenium.open("/");
            selenium.type("//div[@id='gs_lc0']/input", "type some random text");
            selenium.click("//div[@id='gbqfbw']/button");
        }
    
        @After
        public void tearDown() throws Exception {
            selenium.stop();
        }
    }