每次运行脚本时,请帮我从国家/地区名称下拉列表中选择一个随机国家/地区名称。
我想尝试使用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>
countryname.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("---------------------------------------");
}
但是我得到空指针异常。任何人都可以帮我解决代码中的问题
答案 0 :(得分:0)
在java / selenium测试脚本中
答案 1 :(得分: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);
}