使用Selenium从XML文件填充表单

时间:2016-05-17 14:24:00

标签: java xml selenium automation

编辑:没关系,我想通了。不得不By.name()代替By.id()

我正在尝试学习如何将Selenium与XML文件一起使用,但似乎遇到了问题。

步骤:

  • 我解析XML文件并将值保存到字符串
  • 使用Selenium WebDriver,我打开Goog​​le并尝试在搜索框中插入一些值并点击“Google搜索”。

这是我被卡住的地方。永远不会输入该值,也不会点击该按钮。

XML文件:

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

<TestData>
    <url-name>
        <url>http://www.google.com</url>
    </url-name>

    <user-details>
        <email>test203@gmail.com</email>
        <phone>(555)5559292</phone>
        <folder>inbox</folder>
    </user-details>
</TestData> 

Java代码:

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
            Thread.sleep(2000);

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

            wd.close();

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

浏览器会打开,但它只会停留在Google主页上。任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:2)

&#39; Q&#39;和&#39; btnK&#39;是元素名称而不是ID。试试这个。

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