m.o m.o - 1 year ago 48
Java Question

Using Selenium to fill forms from XML file

EDIT: Never mind, I figured it out. Had to do

instead of

I am trying to learn how to use Selenium with XML files but seem to have run into a problem.


  • I parse the XML file and save the values into strings

  • Using Selenium WebDriver, I open up Google and try to insert some value in the search box and hit "Google Search".

This is where I get stuck. The value is never inputted and it never clicks the button.

XML File:

<?xml version="1.0" encoding="UTF-8"?>



Java Code:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import org.w3c.dom.*;

public class XMLTest
public static void main(String [] args)
try {
// Get xml file
File file = new File("input.xml");

// Prepare XML
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);

String url = document.getElementsByTagName("url").item(0).getTextContent();
String email = document.getElementsByTagName("email").item(0).getTextContent();
String phone = document.getElementsByTagName("phone").item(0).getTextContent();
String folder = document.getElementsByTagName("folder").item(0).getTextContent();

System.out.println("\n [Debug Info]\n ------------"
+ "\n Mail:\t\t" + url
+ "\n Email:\t\t" + email
+ "\n Phone:\t\t" + phone
+ "\n Folder:\t" + folder);

// Selenium code
WebDriver wd = new FirefoxDriver();

wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
wd.get(url); // Go to URL
wd.findElement(By.id("q")).sendKeys(phone); // Type into google search box
wd.findElement(By.id("btnK")).click(); // Click button

System.out.println("\n\n [Selenium]\n -----------");
System.out.println("\n Title:\t\t" + wd.getTitle()
+ "\n URL:\t\t" + wd.getCurrentUrl());


} catch(Exception e) {

The browser opens but it just stays on the Google homepage. Any help would be appreciated, thank you!

Answer Source

'q' and 'btnK' are element names and not Ids. Try this.

 wd.findElement(By.name("q")).sendKeys(phone); // Type into google search box
 wd.findElement(By.name("btnK")).click(); // Click button