11

I have this xpath: //*[@id="someId::button"]

Pressing it shows a dropdown list of values.

Now, I know all the elements in the list have an id like this :

//*[@id="someId--popup::popupItemINDEX"]

, where INDEX is a number from 1 to whatever the number of options are.

I also know the value which I must click.

One question would be: since I will always know the id of the button which generates the dropdown, can I get all the elements in the dropdown with a reusable method? (I need to interact with more than one dropdown)

The way I thought about it is: get the root of the initial ID, as in:

//*[@id="someId 

then add the rest : --popup::popupItem. I also need to add the index and I thought I could use a try block (in order to get though the exceptions when I give a bigger than expected index) like this:

 for(int index=1;index<someBiggerThanExpectedNumber;index++){
     try{
         WebElement aux= driver.findElement(By.xpath(builtString+index+"\"]"));
         if(aux.getText().equals(myDesiredValue))
             aux.click();
     }catch(Exception e){}
 }

Note that I am using the webdriver api and java.

I would like to know if this would work and if there is an easier way of doing this, given the initial information I have.

EDIT: The way I suggested works, but for an easier solution, the accepted answer should be seen

4

3 回答 3

12

根据经验,如果可能,请尝试通过一个查询选择更多元素。逐个搜索许多元素将变得非常缓慢。

如果我很好地了解您的需求,那么这样做的好方法是使用

driver.findElement(By.id("someId::button")).click();
driver.findElement(By.xpath("//*[contains(@id, 'someId--popup::popupItem') " +
    "and text()='" + myDesiredValue + "']"))
    .click();

有关 XPath 的更多信息,请参阅规范。如果您可以跳过废话,这将是一本非常好的读物!

这将查找并单击文本等于所需值的元素,该元素的 ID 中包含“someId--popup::popupItem”。

List<WebElement> list = driver.findElements(By.xpath("//*[contains(@id, 'someId--popup::popupItem')]"));

这会找到所有在其 ID 中包含“someId--popup::popupItem”的元素。然后,您可以遍历列表并查找所需的元素。

你知道你可以调用findElement()一个WebElement来搜索它的孩子吗?-driver.findElement(By.id("someId")).findElements(By.className("clickable"))

如果不了解底层 HTML,我想我无法提供最好的方法,但我有一些想法。

于 2012-05-22T08:58:22.323 回答
3

您是否尝试过使用JavascriptExecutor

如果您愿意编写一点 JavaScript,那么这将比在 java 中简单(我认为)

您需要做的就是让一些 JavaScript 爬过 DOM 子树,并返回与您的条件匹配的 DOM 元素列表。然后,WebDriver 将像List<WebElement>在 java 世界中一样愉快地编组它。

于 2012-05-22T08:58:13.323 回答
1

在这里使用的更安全的方法是

int size=driver.findElements(By.xpath("//*[@id='someId::button']")).size();

Start using Index Now

String builtString="//*[@id='someId::button'][";

for(int index=1;index<=size();index++)
{

try
{

   WebElement aux= driver.findElement(By.xpath(builtString+index+"\"]"));

   if(aux.getText().equals(myDesiredValue))
             aux.click();

}
catch(Exception e){}

}

请让我知道上述funda是否有效。

于 2014-04-09T09:10:31.673 回答