0

每次运行脚本时,请帮助我从国家名称下拉列表中选择一个随机国家名称。

我想尝试使用 xml。

下拉菜单的 XPATH 是 .//*[@id='intselect']

HTML code:
<select id="intselect" name="intselect" onchange="setCurrency(this);">
<option value="US">UNITED STATES</option>
<option value="AG">ANTIGUA AND BARBUDA</option>
<option value="AR">ARGENTINA</option>
<option value="AW">ARUBA</option>
<option value="AU">AUSTRALIA</option>
<option value="AT">AUSTRIA</option>
<option value="BH">BAHRAIN</option>
<option value="BD">BANGLADESH</option>
</select>

国名.xml

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

<array name="testArray">

<country>
<countryname>UNITED STATES</countryname>
</country>
<country>
<countryname>ANTIGUA AND BARBUDA</countryname>
</country>
<country>
<countryname>ARGENTINA</countryname>
</country>
<country>
<countryname>ARUBA</countryname>
</country>
<country>
<countryname>AUSTRALIA</countryname>
</country>
</array>

//从XML中获取随机值的方法

public void Fetch_XML()
      {

             SAXBuilder builder = new SAXBuilder();
             File xmlFile = new File("C:\\Documents and Settings\\vlakshm\\MyTNG\\list\\countrynames.xml");
             Element node = null;
             try {

              //Element result=null;
            Document document = (Document) builder.build(xmlFile);
            Element rootNode = document.getRootElement();
            List list = rootNode.getChildren("country");

            Random random = new Random();
            int newcountryname= random.nextInt(list.size());

            node = (Element) list.get(newcountryname);

             }//End of Try loop
             catch (IOException io) {
            System.out.println(io.getMessage());
             } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
             }
             node.getChildText("countryname");
             //element_array = driver.findElement(By.xpath("//select[@id='intselect']/option"));
         }//End of randomPartnum method

// 我正在调用该方法以在下拉列表中进行选择

public void Choser() {
      Fetch_XML();
      driver.findElement(By.id("intselect")).click();      
        System.out.println("---------------------------------------");
        System.out.println("Country choser layer test case-Success");
        System.out.println("---------------------------------------");

  } 

但是我得到空指针异常。谁能帮我解决代码中的问题

4

2 回答 2

0

这对我有用:

private void randomSelect(String id) {
    WebElement webElement = driver.findElement(By.id(id));

    Select select = new Select(webElement);

    List<WebElement> selections = select.getOptions();

    int index = (int)( Math.random() * selections.size());

    select.selectByIndex(index);
}
于 2013-09-26T13:23:17.320 回答
0

在您的 java/selenium 测试脚本中

  1. 获取测试数据数组长度
  2. 在 0-LengthOfArray-1 范围内生成随机数(在给定范围内生成随机数
  3. 使用上面的数字从测试数据数组中选择一个国家
于 2013-06-11T05:27:04.443 回答