0

我正在尝试使用 java 代码自动化测试用例。我使用 selenium 服务器库。现在,当我到达某个页面时,我得到一个包含一定数量元素的下拉框。下拉框称为“类型'。现在我想要做的是单击我想要展开的下拉框,以便在下一步我能够单击特定项目,例如。摇滚/金属/流行音乐等。以上所有内容我都在尝试自动化,但每次我这样做时都会抛出相同的异常:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[@id='Genre']"}

我已经尝试了 By 可用的各种方法,即 By.xpath、By.name、By.id 等,但无济于事。因此,我复制了与“流派”框相关的粘贴信息供您参考。请指导我使用哪种方法使用,以便我可以成功实现我刚才描述的目标。

当我突出显示流派给我时查看选择源:

<td id="genre" width="50%">
                                                                Genre <br><select name="Genre" id="Genre" class="input_boxbbb" onchange="subgener(this.value)"><option value="0000">All</option><option value="26">AIRTEL JINGLE</option><option value="19">ARTISTS</option><option value="27">BATTERY</option><option value="25">BOLLYWOOD</option><option value="28">
4

2 回答 2

1

Ok so the code Pavel suggested is correct and should work.

i have just one comment about it. instead of iterating over all options manually you can just use one the following:

genres.selectByIndex(int index)
genres.selectByValue(String value) 
genres.selectByVisibleText(String text) 

the problem is with the HTML, notice you have 2 elements with the same id but a different case.

<td id="genre" width="50%">
<select name="Genre" id="Genre">

this may cause problems in curtain browsers and is in general bad practice.

if you control the HTML i would suggest changing the id of the <td> element to something else and use the above code.

if you are not the one writing the the HTML try using

Select genre = new Select(driver.findElementBy(By.name("Genre"))) [Notice the Case sensetivity];

if even that doesn't work try this to inspect all <select> elements in the page and use it to pick the one you need:

List<WebElement> selects = driver.findElementsBy(By.tagName("select"));
for (WebElement select : selects) {
   System.out.println(select)
}

hope it helps

于 2012-05-11T09:51:14.590 回答
0

假设您正在使用 WebDriver。稍后的driver变量被认为是有效的 Webdriver 实例:

public void selectGenre(String genreName){ 
   Select genres = new Select(driver.findElement(By.id("genre")));
   List<WebElement> options = new ArrayList<WebElement>;
   options = genres.getOptions();
   for (WebElement genre:options){
       if(genre.getText().equals(genreName)){
           genre.click();
       }
   }
}
于 2012-05-11T08:38:41.383 回答